Dynamic block for optional elements

Viewed 325

I have dynamic block on a variable.

  dynamic "settings" {
    for_each = var.settings
    content {
      id      = lookup(settings.value, "id", null)
      ...
    }
  }

But from the calling module, it not necessary that settings to always exists and sometime it would just be passed null.

settings = null

However, when this happens I get following while planning.

var.settings is null
Cannot use a null value in for_each.

So basically, I only want to dynamic block generation when the settings is not null. How best can I address this?

1 Answers

In this situation, you would not normally want to assign a list or map type variable to null to designate an undefined value. You would want to use the empty constructors [] for list and {} for map instead. This will give you the behavior you desire and promote clean code.

If you really want to assign null to a non string or number type, then you can use the coalesce function with a null coalescing pattern (some languages provide operators for this; e.g. ?: in JS):

for_each = coalesce(var.settings, [])

and that will give you the behavior you desire. Note that it basically adds another layer to use the empty constructor as a backup/default, which is the best practices pattern advised at the beginning of the answer.

Related