第 3 章 过滤的集成资源


3.1. 使用示例代码片段自动创建和发送报告

重要

创建过滤的 Google Cloud 集成后,您可以自动创建并发送报告。主要任务包括查询数据、格式化和导出 CSV 文件,并将数据发送到成本管理。以下示例提供了您引导的代码片段,但您应该调整流程以反映您的独特环境。如果您遵循在没有自定义的情况下编写的文档,则自动化可能不适用于您的特定设置。

以下代码将 CSV 文件从查询数据写入 Google Cloud 存储桶:

import csv
from google.cloud import storage

storage_client = storage.Client()
bucket = storage_client.bucket(“my_bucket”)
for rows in query_job:
    csv_file = "my_report_location/2025-04-01.csv"
    blob = bucket.blob(csv_file)
    with blob.open(mode='w') as f:
        writer = csv.writer(f)
        writer.writerow([my_col_1, my_col_col2])
        writer.writerows(rows)

以下代码添加了批处理来限制 CSV 文件大小:

def batch(iterable, n):
"""Yields successive n-sized chunks from iterable"""
	it = iter(iterable)
	while chunk := tuple(islice(it, n)):
    	yield chunk

for i, rows in enumerate(batch(query_job, 200000)):
    # write csv file code block #

以下代码验证并通过您的服务帐户令牌获取和使用您的服务帐户令牌将报告发送到处理成本:

import os
import requests

# os.getenv(var) used to fetch Google Cloud stored secrets shared with your function
CLIENT_ID = os.getenv('client_id')
CLIENT_SECRET = os.getenv('client_secret')

# Get access token
token_url = 'https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token'
token_headers = {'Content-Type': 'application/x-www-form-urlencoded'}
token_data = {"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "grant_type": "client_credentials"}
access_token = requests.post(token_url, headers=token_headers, data=token_data).json().get("access_token")

# Send reports to Red Hat
json_data = {"source": 0, "reports_list": ["my-file1.csv", "my-file-2.csv"], "bill_year": "2025", "bill_month": "07"}
headers = {'Authorization': f'Bearer {access_token}', 'Accept': 'application/json'}
requests.post("https://console.redhat.com/api/cost-management/v1/ingress/reports/", json=json_data, headers=headers)

3.1.1. 其他资源

仅供参考,此 python 脚本 提供了额外的逻辑,如限制 CSV 文件大小和将变量用于客户端 secret。

有关自动化的额外帮助,请参阅 Google 文档:

Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

关于红帽文档

Legal Notice

Theme

© 2026 Red Hat
返回顶部