如何使用动态阈值对 Datadog 监视器进行 Terraform

如何使用动态阈值对 Datadog 监视器进行 Terraform

我正在尝试从 DataDog 提供商创建大量资源。我希望对每个资源进行尽可能少的定义。许多属性都有一些合理的默认值。我很难决定如何处理监控阈值,特别是有些可能是可选的。

resource "datadog_monitor" "monitor" {
  for_each = {
    faulty_deploy = {
      message    = "A deployment failed."
      name       = "Deployment Failure"
      query      = "someLongQuery"
      type       = "alert"
      thresholds = {critical = "0"}
    }
  }

  message            = each.value["message"]
  query              = each.value["query"]
  name               = each.value["name"]
  type               = each.value["type"]
  escalation_message = coalesce(each.value["escalation_message"], "")
  evaluation_delay   = coalesce(each.value["evaluation_delay"], "0")
  include_tags       = coalesce(each.value["include_tags"],"true")
  
  dynamic "monitor_thresholds" {
    for_each = each.value["thresholds"]
    iterator = threshold
    content {
      # Dynamically adding these properties is the issue.
      "${threshold.key}" = threshold.value
    }
  }

  # These and more would use coalesce to set defaults.
  new_group_delay      = "60"
  notify_audit         = "false"
  on_missing_data      = "default"
  priority             = "0"
  renotify_interval    = "0"
  renotify_occurrences = "0"
  require_full_window  = "false"
  tags                 = []
  timeout_h            = "0"
}

鉴于某些阈值可能设置也可能不设置,如何以这种方式添加动态属性?它们是否应该始终存在0""可以选择覆盖?

答案1

简而言之,你不能。

但是,您可以monitor_thresholds在所有情况下包含具有默认值的嵌套架构。给定与问题中列出的相同格式:

monitor_thresholds {
  critical = lookup(each.value["thresholds"], "critical", "")
  warning = lookup(each.value["thresholds"], "warning", "")
}

lookup函数允许缺少密钥,并在缺少密钥时提供默认值。可以使用条件扩展此功能以获得更多可选部分。

monitor_threshold_windows {
  recovery_window = lookup(each.value, "threshold_windows", null) != null ? lookup(each.value["threshold_windows"], "recovery_window", "") : ""
}

相关内容