Nurhun
Nurhun

Reputation: 691

terraform convert list to string dynamically

I need to extract strings from tuple/list generated by for_each.

How to pass "account1" then "account2" in member with each role ?

variable "binding" {
    type = map
    default = {
        "roles/viewer" = [
            "account1",
            "account2",
        ],
        "roles/logging.viewer" = [
            "account1",
            "account2",
        ],
    }
}


resource "google_project_iam_member" "test-sa-binding" {
  project = var.PROJECT_ID

  for_each = var.binding
  role    = each.key 
  member  = ???
}

Thanks,

Upvotes: 0

Views: 1820

Answers (1)

Marcin
Marcin

Reputation: 238867

You have to flatten your variable first:

locals {
  flat_binding = merge([
      for role, accounts in var.binding:
         {
           for idx, account in accounts:
             "${role}-${idx}" => {
               account = account
               role = role
             }
         }
    ]...) # pls, do NOT remove the dots
}

then

resource "google_project_iam_member" "test-sa-binding" {
  project = var.PROJECT_ID

  for_each = local.flat_binding
  role    = each.value["role"] 
  member  = each.value["account"] 
}

Upvotes: 3

Related Questions