Automatically create and send reports with example code snippets

After you create a filtered Google Cloud integration, you can automate creating and sending reports. The main tasks involve querying your data, formatting and exporting a CSV file, and sending the data to cost management.

The following examples provide code snippets to guide you, but you should adapt the process to reflect your unique environments. If you follow the documentation exactly as written without customizations, the automation might not work for your specific setup.

The following code writes CSV files to your Google Cloud bucket from the query data:

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)

The following code adds batching to restrict the CSV file size:

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 #

The following code authenticates and sends reports to cost management for processing by fetching and using your service account access token:

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)