Problem
When creating Azure Monitor Diagnostic Settings with the azurerm_monitor_diagnostic_setting resource using dynamic blocks, you may encounter validation or API errors during terraform apply. These errors typically occur when log and metric categories are driven by variables.
You may receive one of the following errors.
Error 1: Missing Category
one of 'enabled_log, enabled_metric, metric' must be specified
Error 2: Invalid Category
unexpected status 400 (400 Bad Request) with response: {"code":"BadRequest","message":"Category 'AllLogs' is not supported."Cause
These errors are due to specific requirements from the Azure Monitor API.
Cause of Error 1: Empty Diagnostic Configuration
Azure Monitor requires at least one log or metric category to be configured for each diagnostic setting. This error occurs if your Terraform configuration results in both the diag_logs and diag_metrics variables evaluating to empty lists. When this happens, Terraform does not generate any enabled_log or enabled_metric blocks, and the Azure API rejects the empty configuration.
Cause of Error 2: Incorrect Log Attribute Usage
This error occurs when the value AllLogs is passed as a category argument. In Azure Monitor, AllLogs is a category group, not a category, and must be specified using the category_group argument. Passing it to the incorrect argument results in a 400 Bad Request error from the API.
Solution
At least one diagnostic input (
diag_logsordiag_metrics) must be provided.Logs and metrics can be configured independently or together.
Log groups such as
AllLogsmust usecategory_group.Metric categories such as
AllMetricsmust usecategory.Avoid configurations where both logs and metrics resolve to empty lists.
Validate inputs when building reusable modules to prevent invalid configurations.
The following example demonstrates a correct implementation using a for_each loop and dynamic blocks that properly assign categories and category groups.
Example Configuration
This configuration uses input variables to dynamically create diagnostic settings for logs and metrics.
main.tf
resource "azurerm_monitor_diagnostic_setting" "this" {
for_each = {
for k, v in var.diag_options : k => v
if var.enable_diagnostics
}
name = "my-vnet-diagnostics"
storage_account_id = azurerm_storage_account.this.id
target_resource_id = azurerm_virtual_network.this.id
dynamic "enabled_log" {
for_each = each.value.diag_logs
content {
category_group = enabled_log.value
}
}
dynamic "enabled_metric" {
for_each = each.value.diag_metrics
content {
category = enabled_metric.value
}
}
}terraform.tfvars
diag_options = {
logs = {
log_type = "activity_logs"
settings_name = "logs"
diag_logs = ["AllLogs"]
diag_metrics = []
}
metrics = {
log_type = "resource_logs"
settings_name = "metrics"
diag_logs = []
diag_metrics = ["AllMetrics"]
}
}
Additional Information
For more details on the available arguments, refer to the azurerm_monitor_diagnostic_setting resource documentation.