How to get billing cost of GCP project using python

738 views Asked by At

I am trying to get billing cost of GCP project, but I could not see expected result for the client library that I am using in my code.

I want to get report or spend cost for current month, but it just providing me:

project_id: "my-project"
billing_account_name: "billingAccounts/XXXXX-XXXXX-XXXXX"
billing_enabled: true

I am using billing_v1.GetProjectBillingInfoRequest() class to get result.

from google.cloud import billing_v1
from google.oauth2 import service_account

info = {
    "client_email": "[email protected]",
    "private_key_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "private_key": "-----BEGIN PRIVATE KEY-----xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "token_uri": "https://oauth2.googleapis.com/token"
}
credentials = service_account.Credentials.from_service_account_info(info)

# Create a client
client = billing_v1.CloudBillingClient(credentials=credentials)
def sample_get_project_billing_info():
    # Initialize request argument(s)
    request = billing_v1.GetProjectBillingInfoRequest(
        name="projects/my-project"
    )

    # Make the request
    response = client.get_project_billing_info(request=request)

    # Handle the response
    print(response)
sample_get_project_billing_info()

output:
project_id: "my-project"
billing_account_name: "billingAccounts/XXXX-XXXX-XXXX"
billing_enabled: true
1

There are 1 answers

0
Anirudh Murali On

As John has pointed, there is only one option if you want to get the costs programatically. It is through the billing exports (Standard usage cost exports, Detailed cost exports). You can set it up by following GCP's documentation https://cloud.google.com/billing/docs/how-to/export-data-bigquery.

Once the data starts exporting, you can run queries with filters such as project-id="xyz" or service-name="Dataflow".

If you have multiple projects under an Organization, but with the same billing account, you can run complex queries to identify the cost of each project, or each service, or even cost of a single SKU.

You can integrate this billing export table with a third-party service like Economize to visualize your entire organization's cost broken down by dimensions like projects, services, SKUs.

GCP cost per project