0

I'm attempting to create a number of resources from the DataDog provider. I'm hoping to have to define as little as possible for each resource. For many properties there is some sensible default. I am having difficulty in deciding how to handle monitor thresholds, specifically that some may be optional.

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"
}

Given that some thresholds may or may not be set how does one add dynamic properties in this way? Should they all always exist as 0 or "" and be optionally overwritten?

Marshall Davis
  • 143
  • 1
  • 6

1 Answers1

0

In short, you can't.

You can, however, include the monitor_thresholds nested schema with defaults in all cases. Given the same format as listed in the question:

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

The lookup function allows for a missing key and provides for a default if so. This can be expanded with a conditional for further optional sections.

monitor_threshold_windows {
  recovery_window = lookup(each.value, "threshold_windows", null) != null ? lookup(each.value["threshold_windows"], "recovery_window", "") : ""
}
Marshall Davis
  • 143
  • 1
  • 6