terraform ressources dependency management with google cloud iam

I am still in the process of learning terraform.

I am trying to deploy a cloudSQL database and provide a default service account to access it.

the following piece of code does not work :

# create default service account
resource "google_service_account" "default_service_account" {
  account_id   = "${var.database_name}-${random_id.db_name_suffix.hex}"
  display_name = "Cloud SQL default Service Account for ${var.database_name}-${random_id.db_name_suffix.hex}"
}

# grant role sqlUser for default service account
resource "google_project_iam_member" "iam_binding_default_service_account" {
  project = var.project_id
  role    = "roles/cloudsql.instanceUser"
  member  = "serviceAccount:${default_service_account.account_id}.${module.project.project_id}.iam.gserviceaccount.com"
  depends_on = [
    google_service_account.default_service_account,
  ]
}

terraform plan complains with :

Error: Reference to undeclared resource

  on database.tf line 78, in resource "google_project_iam_member" "iam_binding_default_service_account":
  78:   member  = "serviceAccount:${default_service_account.account_id}.${module.project.project_id}.iam.gserviceaccount.com"

A managed resource "default_service_account" "account_id" has not been
declared in the root module.

I do not understand why the depends_on piece of code does not seem to work and why terraform does not create the default_service_account before trying to populate the iam_binding_default_service_account ?

It should be (forgot google_service_account):

member  = "serviceAccount:${google_service_account.default_service_account.account_id}.${module.project.project_id}.iam.gserviceaccount.com}"

Leave a Comment