Set and retrieve Compute Engine usage export bucket
Stay organized with collections
Save and categorize content based on your preferences.
This sample shows you how to set and retrieve the Compute Engine usage export bucket for a project. The usage export bucket is a Google Cloud Storage bucket where Compute Engine usage reports are stored. The usage reports can be used for billing and cost management purposes.
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License
, and code samples are licensed under the Apache 2.0 License
. For details, see the Google Developers Site Policies
. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis sample demonstrates how to configure a Google Cloud Storage bucket to store Compute Engine usage reports.\u003c/p\u003e\n"],["\u003cp\u003eUsage reports stored in the designated bucket can be used to manage billing and costs related to Compute Engine.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eset_usage_export_bucket\u003c/code\u003e function allows you to specify the bucket and an optional report name prefix, which defaults to "usage_gce" if not specified.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eget_usage_export_bucket\u003c/code\u003e function retrieves the current usage export settings, automatically replacing an empty report name prefix with the default "usage_gce".\u003c/p\u003e\n"],["\u003cp\u003eAuthentication to Compute Engine uses Application Default Credentials.\u003c/p\u003e\n"]]],[],null,["# Set and retrieve Compute Engine usage export bucket\n\nThis sample shows you how to set and retrieve the Compute Engine usage export bucket for a project. The usage export bucket is a Google Cloud Storage bucket where Compute Engine usage reports are stored. The usage reports can be used for billing and cost management purposes.\n\nCode sample\n-----------\n\n### Python\n\n\nBefore trying this sample, follow the Python setup instructions in the\n[Compute Engine quickstart using\nclient libraries](/compute/docs/api/using-libraries).\n\n\nFor more information, see the\n[Compute Engine Python API\nreference documentation](/python/docs/reference/compute/latest).\n\n\nTo authenticate to Compute Engine, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n from __future__ import annotations\n\n import sys\n from typing import Any\n\n from google.api_core.extended_operation import ExtendedOperation\n from google.cloud import compute_v1\n\n\n\n\n\n\n def wait_for_extended_operation(\n operation: ExtendedOperation, verbose_name: str = \"operation\", timeout: int = 300\n ) -\u003e Any:\n \"\"\"\n Waits for the extended (long-running) operation to complete.\n\n If the operation is successful, it will return its result.\n If the operation ends with an error, an exception will be raised.\n If there were any warnings during the execution of the operation\n they will be printed to sys.stderr.\n\n Args:\n operation: a long-running operation you want to wait on.\n verbose_name: (optional) a more verbose name of the operation,\n used only during error and warning reporting.\n timeout: how long (in seconds) to wait for operation to finish.\n If None, wait indefinitely.\n\n Returns:\n Whatever the operation.result() returns.\n\n Raises:\n This method will raise the exception received from `operation.exception()`\n or RuntimeError if there is no exception set, but there is an `error_code`\n set for the `operation`.\n\n In case of an operation taking longer than `timeout` seconds to complete,\n a `concurrent.futures.TimeoutError` will be raised.\n \"\"\"\n result = operation.result(timeout=timeout)\n\n if operation.error_code:\n print(\n f\"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}\",\n file=sys.stderr,\n flush=True,\n )\n print(f\"Operation ID: {operation.name}\", file=sys.stderr, flush=True)\n raise operation.exception() or RuntimeError(operation.error_message)\n\n if operation.warnings:\n print(f\"Warnings during {verbose_name}:\\n\", file=sys.stderr, flush=True)\n for warning in operation.warnings:\n print(f\" - {warning.code}: {warning.message}\", file=sys.stderr, flush=True)\n\n return result\n\n\n def set_usage_export_bucket(\n project_id: str, bucket_name: str, report_name_prefix: str = \"\"\n ) -\u003e None:\n \"\"\"\n Set Compute Engine usage export bucket for the Cloud project.\n This sample presents how to interpret the default value for the\n report name prefix parameter.\n\n Args:\n project_id: project ID or project number of the project to update.\n bucket_name: Google Cloud Storage bucket used to store Compute Engine\n usage reports. An existing Google Cloud Storage bucket is required.\n report_name_prefix: Prefix of the usage report name which defaults to an empty string\n to showcase default values behaviour.\n \"\"\"\n usage_export_location = compute_v1.UsageExportLocation()\n usage_export_location.bucket_name = bucket_name\n usage_export_location.report_name_prefix = report_name_prefix\n\n if not report_name_prefix:\n # Sending an empty value for report_name_prefix results in the\n # next usage report being generated with the default prefix value\n # \"usage_gce\". (ref: https://cloud.google.com/compute/docs/reference/rest/v1/projects/setUsageExportBucket)\n print(\n \"Setting report_name_prefix to empty value causes the report \"\n \"to have the default prefix of `usage_gce`.\"\n )\n\n projects_client = compute_v1.ProjectsClient()\n operation = projects_client.set_usage_export_bucket(\n project=project_id, usage_export_location_resource=usage_export_location\n )\n\n wait_for_extended_operation(operation, \"setting GCE usage bucket\")\n\n\n\n\n def get_usage_export_bucket(project_id: str) -\u003e compute_v1.UsageExportLocation:\n \"\"\"\n Retrieve Compute Engine usage export bucket for the Cloud project.\n Replaces the empty value returned by the API with the default value used\n to generate report file names.\n\n Args:\n project_id: project ID or project number of the project to update.\n Returns:\n UsageExportLocation object describing the current usage export settings\n for project project_id.\n \"\"\"\n projects_client = compute_v1.ProjectsClient()\n project_data = projects_client.get(project=project_id)\n\n uel = project_data.usage_export_location\n\n if not uel.bucket_name:\n # The usage reports are disabled.\n return uel\n\n if not uel.report_name_prefix:\n # Although the server sent the empty string value, the next usage report\n # generated with these settings still has the default prefix value\n # \"usage_gce\". (see https://cloud.google.com/compute/docs/reference/rest/v1/projects/get)\n print(\n \"Report name prefix not set, replacing with default value of \"\n \"`usage_gce`.\"\n )\n uel.report_name_prefix = \"usage_gce\"\n return uel\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=compute)."]]