You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python通过Billing API获取GCP项目账单及VM月度成本

使用Python获取GCP账单信息(含VM月度成本查询)

前置准备

  • 启用Cloud Billing API:在GCP控制台的API库中找到并启用Cloud Billing API
  • 配置权限:确保执行代码的账号(用户或服务账号)拥有Billing Account Viewer或Billing Account Administrator角色,具备billing.costs.get权限
  • 安装客户端库:
    pip install google-cloud-billing
    
  • 认证配置:设置环境变量指向服务账号密钥文件,或使用gcloud CLI登录认证:
    export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account-key.json"
    

通过Billing API获取项目账单(含VM月度成本)

以下代码示例实现查询指定月份内每台VM实例的汇总成本,核心是利用query_cost_report接口按VM实例分组筛选费用:

from google.cloud import billing_v1
from google.cloud.billing_v1.types import QueryCostReportRequest, Date

def get_vm_monthly_cost(billing_account_id, target_year, target_month):
    # 初始化Billing客户端
    client = billing_v1.CloudBillingClient()
    
    # 构建时间范围:左闭右开,覆盖整个目标月份
    start_date = Date(year=target_year, month=target_month, day=1)
    # 计算结束日期(次月1日)
    if target_month == 12:
        end_date = Date(year=target_year + 1, month=1, day=1)
    else:
        end_date = Date(year=target_year, month=target_month + 1, day=1)
    
    # 构造查询请求:按VM实例名称分组,筛选Compute Engine实例费用
    query_request = QueryCostReportRequest(
        name=f"billingAccounts/{billing_account_id}",
        date_range_start=start_date,
        date_range_end=end_date,
        group_by=["resource.name"],  # 按VM实例名称分组
        filter='service.description:"Compute Engine" AND resource.type:"gce_instance"'  # 仅筛选VM相关费用
    )
    
    # 执行查询并处理结果
    response = client.query_cost_report(query_request)
    for row in response.rows:
        vm_instance_name = row.group_keys[0].value
        total_cost = row.cost_amount.value
        currency = row.cost_amount.currency_code
        print(f"VM实例 [{vm_instance_name}] 在 {target_year}年{target_month}月 的总成本: {total_cost:.2f} {currency}")

# 调用示例
if __name__ == "__main__":
    # 替换为你的GCP账单账号ID(格式:0X0X0X-0X0X0X-0X0X0X)
    YOUR_BILLING_ACCOUNT_ID = "000000-000000-000000"
    get_vm_monthly_cost(YOUR_BILLING_ACCOUNT_ID, 2024, 5)

关键说明

  • 账单账号ID:可在GCP账单页面的"账单账号"详情中找到,格式为0X0X0X-0X0X0X-0X0X0X
  • 筛选逻辑:filter参数可进一步细化,比如添加区域筛选resource.location:"us-central1",或排除特定标签的实例
  • 费用汇总:group_by=["resource.name"]会将同一VM实例的所有关联费用(CPU、磁盘、网络等)自动汇总
  • 时间范围:API采用左闭右开的时间区间,因此结束日期需设为目标月份的次月1日,确保覆盖整个目标月份

内容的提问来源于stack exchange,提问作者Daniel Vanum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 14:15:24