How to put a condition on a for_each

Hello,

How can I put a condition on a for_each ? I need to execute the for_each only if the value is not NULL

I have a ressource who get informations from a YAML file :

alert_email:
- name: “Name 1”
query: “Query”

resource “logdna_view” “my_alert_mail” {
for_each = { for x in local.input.alert_email : x.name => x}

On the case I have some values “name” under “alert_email”, that will work fine.

But if I delete the “name” block because I don’t want this ressourse anymore, I have the error bellow :

Error: Iteration over null value

│ on maint.tf line 49, in resource “logdna_view” “my_alert_mail”:
│ 49: for_each = { for x in local.input.alert_email : x.name => x}
│ ├────────────────
│ │ local.input.alert_email is null

│ A null value cannot be used as the collection in a ‘for’ expression.

I tried this :

resource “logdna_view” “my_alert_mail” {
for_each = { for x in local.input.alert_email : x.name => x if local.input.alert_email != null }

But I have the same error :

Error: Iteration over null value

│ on maint.tf line 49, in resource “logdna_view” “my_alert_mail”:
│ 49: for_each = { for x in local.input.alert_email : x.name => x if local.input.alert_email != null }
│ ├────────────────
│ │ local.input.alert_email is null

│ A null value cannot be used as the collection in a ‘for’ expression.

Thanks for your help

Hi @Dominique,

Indeed in this case the if clause of the for expression is not a suitable answer because that’s a condition evaluated for each element of the source collection rather than the collection as a whole, and so the error you’ve seen occurs before Terraform evaluates that.

One way to solve this would be to use the coalesce function to provide a fallback value to use whenever the real value is null:

{ for x in coalesce(local.input.alert_email, []) : x.name => x }

The coalesce function checks each of its arguments in turn and returns the first one that isn’t null, so in the above example it will return [] if local.input.alert_email is null, and thus provide a valid empty sequence to the for expression.

In the above I assumed that your source collection is a list. If it’s a map then it would be clearer to use {} instead of [] as the fallback value.

2 Likes

That works now, thank you very much for your help !