Kyle
Kyle

Reputation: 103

Use different value if another resource is created

I have a Terraform module that I would like to modify. Currently my module creates a service account. I would like to modify it so that someone could pass in an existing service account OR if one is not passed in, then the module creates a service account is it would have originally.

Originally my service account looked like this:

resource "google_service_account" "scheduler" {
  account_id = "${var.prefix}-scheduler"
  project    = var.project
}

I've added the following variable to my variables.tf file:

variable "service_account_email" {
  default = null
  description = "Existing service account for running ... jobs.  If null a new service account will be created."
}

What I originally thought to do was to add some locals

locals {
  service_account_count = var.service_account_email == null ? 1 : 0
  service_account_email = var.service_account_email == null ? google_service_account.scheduler.email : var.service_account_email
}

Then I could change my service account to look like

resource "google_service_account" "scheduler" {
  count = local.service_account_count
  account_id = "${var.prefix}-scheduler"
  project    = var.project
}

And then wherever I would have referenced google_service_account.scheduler.email I can instead reference local.service_account_email .. It doesn't look like I'm able to do this, however, for a few reasons.

I get the following error if I try to use the locals block that mentioned above:

│ Because google_service_account.scheduler has "count" set, its attributes must be accessed on specific instances.
│ 
│ F`or example, to correlate with indices of a referring resource, use:
│     google_service_account.scheduler[count.index]
╵

If I change it so that I'm using google_service_account.scheduler[count.index].email instead, I get the following error:

│ Because google_service_account.scheduler has "count" set, its attributes must be accessed on specific instances.
│ 
│ For example, to correlate with indices of a referring resource, use:
│     google_service_account.scheduler[count.index]
╵

Now I'm sort of stuck, because I can't force any resources that would originally have referenced google_service_account.scheduler.email to instead reference the var.service_account_email variable that is being passed in for cases where we would prefer to use an existing service account.

Upvotes: 1

Views: 166

Answers (1)

Marcin
Marcin

Reputation: 238209

Since you are using count, you have to use [0] to access your resource:

service_account_email = var.service_account_email == null ? google_service_account.scheduler[0].email : var.service_account_email

Upvotes: 1

Related Questions