Conditionally create resources when a for_each loop is involved

You can’t have count and for_each on a data source, resource or module.
A trick to filter a map to remove items based on your condition.

variable "mymap" {
    type = map(object({
        attribute = string
        condition = bool
    }))

    default = {
        key1 = {
            attribute = "value"
            condition = true
        }
        key2 = {
            attribute = "value"
            condition = false
        }
        key3 = {
            attribute = "value"
            condition = true
        }
    }
}

resource "null_resource" "test" {
  for_each = { for k in compact([for k, v in var.mymap: v.condition ? k : ""]): k => var.mymap[k] }
}
1 Like