Conditionally create resources when a for_each loop is involved

Hi @chrisadkin,

The key thing about for_each is that it declares one resource instance for each element in the map (or set) assigned to it.

Building on that, the key to your question is to make sure that the for_each map has zero elements in the cases where you want to create nothing. If you have a sort of “all or nothing” situation – where you’ll disable all of the elements together in the “off” case – then a relatively concise way to write it is to write a for expression with an if clause that always evaluates to true only if your condition is enabled:

  for_each = { for k, v in var.some_map : k => v if var.enabled }

Typically when writing an expression like this the if clause would contain a reference to k and/or v, but since this is an “all or nothing” situation the result depends only on some external flag and doesn’t vary for each element.

If you do want to vary the behavior by element then you can certainly do that too. For example:

  for_each = {
    for k, v in var.some_map : k => v
    if contains(var.enabled_keys, k)
  }

(the above is assuming that var.enabled_keys is a set(string) value containing the keys of the var.some_map elements that ought to be enabled, just as a contrived example of an item-specific condition.)

9 Likes