使用 Terraform 创建具有 IAM 角色的服务帐户

Using Terraform to create a service account with IAM roles

我正在尝试使用 Terraform 使用 roles/logging.logWriter IAM 角色创建一个基本服务帐户。以下是我的配置方式:

resource "google_service_account" "log_user" {
  account_id   = "log-user"
  display_name = "Logging User"
}

data "google_iam_policy" "log_policy" {
  binding {
    role = "roles/logging.logWriter"

    members = [
      "serviceAccount:${google_service_account.log_user.email}"
    ]
  }
}

resource "google_service_account_iam_policy" "log_user_policy" {
  service_account_id = "${google_service_account.log_user.name}"
  policy_data        = "${data.google_iam_policy.log_policy.policy_data}"
}

当 运行 terraform apply 我收到以下错误消息:

* module.iam.google_service_account_iam_policy.log_user_policy: 1 error(s) occurred:

* google_service_account_iam_policy.log_user_policy: Error setting IAM policy for service account 'projects/arcadia-apps-237918/serviceAccounts/log-user@arcadia-apps-237918.iam.gserviceaccount.com': googleapi: Error 400: Role roles/logging.logWriter is not supported for this resource., badRequest

从我所做的挖掘中,我似乎无法找到关于如何创建服务帐户然后为其附加角色的明确解释。

我通过执行以下操作解决了这个问题:

resource "google_service_account" "log_user" {
  account_id   = "log-user"
  display_name = "Logging User"
}

resource "google_project_iam_binding" "log_user" {
  project = "arcadia-apps-237918"
  role    = "roles/logging.logWriter"
  members = [
    "serviceAccount:${google_service_account.log_user.email}"
  ]
}

用户 运行 terraform 需要先为其分配 IAM 管理员角色,然后您才能执行此操作。