使用 google cloud iam 进行 terraform 资源依赖管理

terraform ressources dependency management with google cloud iam

我还在学习terraform。

我正在尝试部署一个 cloudSQL 数据库并提供一个默认服务帐户来访问它。

以下代码无效:

# 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 计划抱怨:

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.

我不明白为什么 depends_on 段代码似乎不起作用,为什么 terraform 在尝试填充 iam_binding_default_service_account 之前不创建 default_service_account?

应该是(忘了google_service_account):

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