调用Cloud Billing API遇403权限错误,已配置权限仍无法解决
问题分析与解决方案
核心原因
你配置的Billing Account Usage Commitment Recommender Admin权限仅用于管理用量承诺推荐,没有权限调用billingAccounts.get和billingAccounts.projects.list接口,这是导致403错误的直接原因。
解决步骤
替换为正确的权限
给服务账号添加以下任一权限(根据需求选择最小权限):Billing Account Viewer(角色ID:roles/billing.viewer):允许查看账单账户信息和关联项目列表,适合只读场景。Billing Account Administrator(角色ID:roles/billing.admin):拥有账单账户的全部管理权限,适合需要修改配置的场景。
确认权限绑定层级
确保权限是直接绑定到目标账单账户上,而不是服务账号所在的GCP项目层级。操作路径:- 打开Google Cloud账单控制台,进入目标账单账户的「权限」页面。
- 添加服务账号邮箱,分配上述角色。
代码与配置验证
- 确认
billing_account_id格式正确,必须是billingAccounts/xxxx-xxxx-xxxx(xxxx部分为你的账单账户ID)。 - 检查服务账号JSON密钥文件路径正确,且文件未被篡改。
- 确认
权限生效等待
权限变更后可能需要1-5分钟生效,若刚配置完权限,等待几分钟后再重试代码。
修正后的代码(无需修改,仅权限调整即可)
from google.oauth2 import service_account from googleapiclient.discovery import build # Set service account file path SERVICE_ACCOUNT_FILE = './1.json' # Create credentials credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE) # Build service object service = build('cloudbilling', 'v1', credentials=credentials) # Your billing account ID can be found in the Google Cloud Billing console billing_account_id = 'billingAccounts/xxxx-xxxx-xxxx' # Get billing information billing_info = service.billingAccounts().get(name=billing_account_id).execute() print('Billing Account Info:') print(billing_info) # Get a list of bill items projects = service.billingAccounts().projects().list(name=billing_account_id).execute() print('Projects:') for project in projects.get('projectBillingInfo', []): print(f"{project['projectId']}: {project['billingAccountName']}")
内容的提问来源于stack exchange,提问作者mi zhang
相关产品推荐
相关产品推荐

