You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Terraform的for_each和locals实现Azure多存储类型日志配置

解决Azure存储服务诊断设置重复代码问题

可以通过for_each结合locals消除重复代码,核心是给数据块也添加for_each,让每个存储服务类型都能获取对应的诊断类别数据。以下是正确实现:

步骤说明

  1. 定义本地变量存储需要配置的所有存储服务类型
  2. 为每个服务类型单独拉取诊断类别数据(数据块使用for_each遍历)
  3. 遍历服务类型创建诊断设置,关联对应的数据块结果

完整代码示例

locals {
  storage_services = ["blobServices", "tableServices", "queueServices"]
}

# 为每个存储服务类型获取诊断类别数据
data "azurerm_monitor_diagnostic_categories" "storage_services" {
  for_each   = toset(local.storage_services)
  resource_id = "${azurerm_storage_account.stamp.id}/${each.key}/default/"
}

# 为每个存储服务类型创建诊断设置
resource "azurerm_monitor_diagnostic_setting" "storage_diagnostic_settings" {
  for_each                   = toset(local.storage_services)
  name                       = "storage-${each.key}-diagnostics"
  target_resource_id         = "${azurerm_storage_account.stamp.id}/${each.key}/default/"
  log_analytics_workspace_id = azurerm_log_analytics_workspace.stamp.id

  dynamic "log" {
    iterator = entry
    for_each = data.azurerm_monitor_diagnostic_categories.storage_services[each.key].logs

    content {
      category = entry.value
      enabled  = true

      retention_policy {
        enabled = true
        days    = 30
      }
    }
  }

  dynamic "metric" {
    iterator = entry
    for_each = data.azurerm_monitor_diagnostic_categories.storage_services[each.key].metrics

    content {
      category = entry.value
      enabled  = true

      retention_policy {
        enabled = true
        days    = 30
      }
    }
  }
}

关键修正点

  • 数据块azurerm_monitor_diagnostic_categories添加for_each,与本地变量的服务类型列表绑定,生成每个服务对应的数据源
  • 诊断设置名称包含each.key,避免不同服务的诊断设置重名
  • 引用诊断类别数据时,通过data.azurerm_monitor_diagnostic_categories.storage_services[each.key]关联当前服务的数据源

内容的提问来源于stack exchange,提问作者huju vert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 02:06:04