pkaramol
pkaramol

Reputation: 19452

Reference resource from variable in terraform

I want to create an object through which I will iterate using for_each to create some:

resources

So my object is more or less like this

  service_accounts = {
    "gha_storage_admin_sa" = {
      create       = true
      project      = var.project_id
      account_id   = "id1"
      display_name = "GHA service account 1"
      role         = "roles/storage.admin"
    },
    "gha_cluster_scaling_sa" = {
      create       = false
      project      = var.project_id
      account_id   = "id2"
      display_name = "GHA service account 2"
      role         = google_organization_iam_custom_role.my_custom_role.id
    },
  }
resource "google_service_account" "service_account" {
  for_each = {
    for k, v in local.service_accounts: k => v
        if v.create
  }

  project      = each.value.project
  account_id   = each.value.account_id
  display_name = each.value.display_name
}


resource "google_project_iam_member" "member" {
  for_each = local.service_accounts

  project = var.project_id
  role    = each.value.role
  member  = "serviceAccount:${google_service_account.service_account[each.key].email}"
}

This works fine if the above is a local variable.

I want however to expose it as a regular variable.

My question is whether the referenced resource (google_organization_iam_custom_role.my_custom_role.id) in the second element can be somehow exposed as a variable.

Upvotes: 0

Views: 973

Answers (1)

Marcin
Marcin

Reputation: 239000

My question is whether the referenced resource (google_organization_iam_custom_role.my_custom_role.id) in the second element can be somehow exposed as a variable.

Sadly its not possible. TF does not support dynamic variables. All variables' values must be know at plan time. You have to pass the actual value of google_organization_iam_custom_role.my_custom_role.id as input variable to your code.

Upvotes: 2

Related Questions