解决 Google Cloud 报错 403 Permission denied 服务账号 IAM 角色排查
排查 Google Cloud CLI (gcloud) 与服务账号提示 403 Permission denied on resource 错误,分析 IAM 预设角色与服务账号权限继承。
问题现象
在终端使用 gcloud CLI 或在 GKE/Compute Engine 中调用 Google Cloud API 时,命令报错:
ERROR: (gcloud.compute.instances.list) PERMISSION_DENIED: Required 'compute.instances.list' permission for 'projects/my-project-123'
在 Python 客户端 SDK 中抛出:
google.api_core.exceptions.PermissionDenied: 403 The caller does not have permission
触发根因
Google Cloud IAM 访问控制模型包括身份、角色(Role)、权限(Permission)与组织资源层级:
- 服务账号(Service Account)未授予必要角色:服务账号缺少包含对应具体底层权限(如
compute.instances.list)的预设角色(如roles/compute.viewer); - 目标 API 服务未在项目中启用(API Disabled):即便具备超级管理员角色,若未在项目内启用
compute.googleapis.com,访问依然返回 403; - Compute Engine 默认访问范围(Access Scopes)过窄:创建 VM 实例时选用了默认的作用域,即便绑定了具备管理员角色的服务账号,也受限于 OAuth 范围被直接拦截;
- 组织策略(Organization Policy)约束拦截。
解决步骤
1. 查看当前生效的凭据与服务账号身份
确认当前执行操作的具体主体是谁:
gcloud auth list
如果使用服务账号:
gcloud config get-value account
2. 在项目级别为服务账号授予对应 IAM 角色
在 GCP 控制台或使用命令行绑定角色:
gcloud projects add-iam-policy-binding my-project-123 --member="serviceAccount:my-sa@my-project-123.iam.gserviceaccount.com" --role="roles/compute.viewer"
如果涉及 GCS 存储桶:
gcloud projects add-iam-policy-binding my-project-123 --member="serviceAccount:my-sa@my-project-123.iam.gserviceaccount.com" --role="roles/storage.objectViewer"
3. 确保目标服务的 API 已在项目中启用
检查 API 是否处于开启状态:
gcloud services list --enabled | grep compute
若未开启,执行启用:
gcloud services enable compute.googleapis.com
4. 调整 Compute Engine VM 的 Access Scopes
针对运行在 GCP VM 内部的程序,停止实例并将 Access Scopes 修改为 cloud-platform(全权交由 IAM 角色控制):
gcloud compute instances stop my-vm
gcloud compute instances set-service-account my-vm --service-account=my-sa@my-project-123.iam.gserviceaccount.com --scopes=cloud-platform
gcloud compute instances start my-vm
验证确认
再次运行此前报错的命令:
gcloud compute instances list
终端顺利列出集群中的所有云服务器实例,403 PERMISSION_DENIED 彻底消除。


