GCP服务账号调用IAM API失败,Terraform创建SA遇403权限错误
Terraform服务账号创建新SA时遇403权限错误
问题详情
使用个人项目Owner凭证执行Terraform代码创建服务账号(SA)一切正常,但切换到专用Terraform服务账号gitlab-terraform@xxxxxx.iam.gserviceaccount.com执行时失败。
Terraform代码
module "service_accounts" { source = "terraform-google-modules/service-accounts/google" version = "~> 4.1" project_id = var.project prefix = var.env names = ["dataproc-sa"] project_roles = [ "${var.project}=>roles/cloudkms.cryptoKeyEncrypterDecrypter", "${var.project}=>roles/storage.objectViewer", "${var.project}=>roles/dataproc.worker", ] }
模块要求的权限
根据terraform-google-modules/service-accounts/google模块文档,部署凭证需具备:
- Service Account Admin(
roles/iam.serviceAccountAdmin) - (可选)Service Account Key Admin(
roles/iam.serviceAccountKeyAdmin,仅当generate_keys=true时需要) - (可选)在项目/组织级授予IAM角色所需的对应权限
报错信息
已为Terraform服务账号绑定roles/iam.serviceAccountAdmin,但仍收到:
Error: Error creating service account: googleapi: Error 403: Identity and Access Management (IAM) API has not been used in project xxxxxxxxx before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/iam.googleapis.com/overview?project=xxxxxxxxx then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.
补充:尝试绑定roles/iam.admin角色时,收到错误:
ERROR: Policy modification failed. For a binding with condition, run "gcloud alpha iam policies lint-condition" to identify issues in condition. ERROR: (gcloud.projects.add-iam-policy-binding) INVALID_ARGUMENT: Role roles/iam.admin is not supported for this resource.
解决方法
1. 启用IAM API
错误提示已明确核心问题:IAM API未启用。项目Owner账号执行时会自动触发API启用,但服务账号无此权限,需手动操作:
- 方式一:在Google Cloud控制台的「API和服务」中找到「Identity and Access Management (IAM) API」并启用
- 方式二:使用gcloud命令:
gcloud services enable iam.googleapis.com --project=你的项目ID
2. 补充必要权限
除已绑定的roles/iam.serviceAccountAdmin,还需给Terraform服务账号添加项目IAM绑定权限(代码中需为新SA授予项目级角色):
- 推荐绑定
roles/resourcemanager.projectIamAdmin角色,该角色允许管理项目IAM策略,满足模块中project_roles配置的需求 - 若追求最小权限,可创建自定义角色,包含
resourcemanager.projects.setIamPolicy权限
3. 关于roles/iam.admin报错的说明
roles/iam.admin是组织级角色,无法直接绑定到项目资源,这就是绑定时报错的原因,项目级无需使用该角色。
4. 等待权限传播
完成API启用和权限配置后,等待2-5分钟让配置生效,再重新执行Terraform。
内容的提问来源于stack exchange,提问作者Andrew Saushkin
相关产品推荐
相关产品推荐

