Reference resource from variable in terraform

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

  • google_service_account
  • google_project_iam_member

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.

Hi @pkaramol,

Can you explain a little more about the problem you are having? What exactly are you trying to accomplish by having google_organization_iam_custom_role.my_custom_role.id assigned to a variable within the same module, and why doesn’t a local value work for you?

Note that “locals” are really just variables within the local module scope, while “variables” are inputs assigned outside of the module scope.