第 3 章 过滤的集成资源


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

重要

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

以下代码通过从服务帐户获取访问令牌来通过成本管理进行身份验证:

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

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")

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

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, BATCH_SIZE)):

3.1.1. 其他资源

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

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

Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

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

關於紅帽

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

Theme

© 2026 Red Hat
返回顶部