在 Google Cloud Platform(GCP)中,想要自动化获取和分析你的项目账单,你可以利用 Cloud Billing API。以下是获取账单信息的推荐方式:
import google.auth
from googleapiclient.discovery import build
# 认证
credentials, project = google.auth.load_credentials_from_file("service-account.json")
service = build('cloudbilling', 'v1', credentials=credentials)
# 获取当前账号所有的billing accounts
billing_accounts = service.billingAccounts().list().execute()
for account in billing_accounts.get('billingAccounts', []):
print(account['name'], account['displayName'], account['open'])
GCP 的推荐做法是将详细的账单导出到 BigQuery,然后用 SQL 查询你想要的账单明细。
SELECT service.description AS service, sku.description AS sku, usage_start_time, usage_end_time, cost, currency FROM `YOUR_PROJECT.YOUR_DATASET.gcp_billing_export_v1_*` WHERE _PARTITIONTIME >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 DAY) ORDER BY usage_start_time DESC LIMIT 100
这样可以直观地分析你在 GCP 的消费情况。
虽然 Billing API 无法直接获取详细账单,但你可以结合 Cloud Billing Budgets API 查询预算和花费进度。
希望这些方法能帮助你轻松掌握 GCP 账单自动化获取!如需进一步集成到你的报表系统,可以配合定时任务和邮件推送实现全自动化哦!🚀