如何在Terraform中用Foreach循环遍历数组生成Datadog监控?
批量生成Kubernetes失败Pod的Datadog监控实例
步骤1:定义命名空间与Slack通道的映射
先声明一个map类型变量,存储命名空间和对应Slack告警通道的键值对:
variable "namespace_slack_channels" { type = map(string) default = { "production" = "#prod-alerts" "staging" = "#staging-alerts" "development" = "#dev-alerts" } }
步骤2:用for_each遍历映射生成监控实例
通过datadog_monitor资源的for_each参数遍历上述map,动态替换命名空间和Slack通道配置:
resource "datadog_monitor" "kubernetes_failed_pods" { for_each = var.namespace_slack_channels name = "Kubernetes: Failed pods in ${each.key} namespace" type = "query alert" query = "sum(last_5m):sum(kubernetes.pod.status.phase{namespace:${each.key},phase:failed}) by {pod_name} > 0" message = <<EOT Failed pods detected in *${each.key}* namespace. Notify: ${each.value} EOT tags = ["environment:${each.key}", "monitor:kubernetes-failed-pods"] priority = 3 notification { channel = each.value message = "Failed pods in ${each.key} - check Datadog dashboard for details" } notify_no_data = false renotify_interval = 60 }
核心逻辑说明
for_each = var.namespace_slack_channels:遍历定义的映射集合,每个键值对对应一个独立的监控实例each.key:调用当前遍历项的键(即目标命名空间名称)each.value:调用当前遍历项的值(即对应的Slack告警通道)- 监控查询通过
namespace:${each.key}精准过滤指定命名空间的失败Pod - 告警标题、消息、通知通道均与当前命名空间的配置动态绑定
内容的提问来源于stack exchange,提问作者jssteele89
相关产品推荐
相关产品推荐

