Skipping resource thatr refers to another if condition is met

Dear community

The goal would be: skipping resource if var.sa (list string) is empty.

resource "google_service_account_iam_binding" "binding" {
  for_each = google_service_account.service_accounts
  service_account_id = each.value.name  
  role               = "roles/iam.role"
  members = [
      for list in var.sa : "${list}" 
      ]
}

Is it possibile or approach is wrong?
Thanks

For future reference, solved like this

resource "google_service_account_iam_binding" "binding" {
  for_each = lenght(var.sa) > 0 ? google_service_account.service_accounts : {}
  service_account_id = each.value.name  
  role               = "roles/iam.role"
  members = [
      for list in var.sa : "${list}" 
      ]
}

Hi @igpix! I’m glad you found an answer. Here’s a different way to write it which uses the if clause in a for expression to get essentially the same effect. There’s no strong reason to prefer one over the other in your particular case (when referring directly to a variable) but this for expression answer can generalize to more complex situations when you’d want to do other sorts of projecting or filtering of your collection first:

  for_each = {
    for k, v in google_service_account.service_accounts : k => v
    if length(var.sa) > 0
  }

This achieves the same effect as yours by filtering out all of the elements of the map if the condition doesn’t hold.

What you did is fine too, so I’m not suggesting that you replace this, just sharing another pattern that you might find useful in the future.

1 Like