Tf12 - for_each & 'count' conditional

I’d like to create a few resources if and only if the environment variable is prod.
The pattern I’ve been using relies on env as a variable passed in like:
terraform plan -var "env=prod"

With a variable like this:

variable "lambda_error_threshold" {
  default = {
    "func1" = 10,
    "func2" = 2,
    "func3" = 50,
    "func4" = 100,

I’d like to have one datadog_monitor to iterate over the functions & thresholds defined to create each monitor. Using the idea of count to determine a true/false value, I could do this without a for_each call. Combining the for_each & count would result in this below, but it’s

resource "datadog_monitor" "lambda_error_monitors" {
  count               = var.env == "prod" ? 1 : 0
  for_each            = var.lambda_error_threshold

maybe I can create a more clever variable?
Any suggestions on how I can make this happen?

You can use conditional expressions in for_each too:

resource "datadog_monitor" "lambda_error_monitors" {
  for_each = var.env == "prod" ? var.lambda_error_threshold : {}

  # ...

The above will cause for_each to get an empty map when the condition isn’t true, and therefore you’ll end up with zero instances just as you would when setting count = 0.

1 Like

Interesting syntax, but it works exactly as I intended. Thanks so much!