Google Cloud Asset
The `google-cloud-asset` client library for Python provides programmatic access to the Google Cloud Asset Inventory API. It allows users to track, analyze, and export metadata for Google Cloud resources and IAM policies, maintaining a five-week history of changes. Part of the `google-cloud-python` monorepo, it receives regular updates. The current version is 4.3.0.
Warnings
- breaking Version 4.x of `google-cloud-asset` requires Python 3.9 or newer. Projects using older Python versions (3.8 or below) must upgrade their Python environment or use an older major version of the library.
- gotcha Authentication is primarily handled via Application Default Credentials (ADC). Misconfiguration of ADC, such as not running `gcloud auth application-default login` for local development or not attaching a service account to a production workload, will result in authentication errors.
- gotcha The library's logging can contain sensitive information. By default, logging events are not handled. If enabled, ensure that log storage and access are properly secured to prevent exposure of sensitive metadata.
- gotcha Many API calls require a correctly formatted 'scope' (e.g., `projects/PROJECT_ID`, `folders/FOLDER_ID`, or `organizations/ORG_ID`). Incorrectly formatted resource names or scopes are a common source of API errors.
Install
-
pip install google-cloud-asset
Imports
- AssetServiceClient
from google.cloud import asset_v1 client = asset_v1.AssetServiceClient()
- Asset
from google.cloud import asset_v1 asset = asset_v1.Asset()
Quickstart
import os
from google.cloud import asset_v1
def list_all_assets(project_id: str):
"""Lists all assets in a given project."""
if not project_id:
raise ValueError("GOOGLE_CLOUD_PROJECT environment variable not set. Please set it or provide a project ID directly.")
client = asset_v1.AssetServiceClient()
# The scope can be a project, folder, or organization
# Example: 'projects/YOUR_PROJECT_ID', 'folders/YOUR_FOLDER_ID', 'organizations/YOUR_ORG_ID'
parent_scope = f"projects/{project_id}"
# Call the API to search all resources. Returns all asset types by default if none are specified.
request = asset_v1.SearchAllResourcesRequest(scope=parent_scope)
print(f"Listing assets for scope: {parent_scope}")
try:
for asset in client.search_all_resources(request=request):
print(f"Asset Name: {asset.name}, Type: {asset.asset_type}, State: {asset.state}")
except Exception as e:
print(f"Error listing assets: {e}")
if __name__ == "__main__":
# Set this environment variable or replace directly with your GCP Project ID
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "")
# For local development, ensure Application Default Credentials (ADC) are set up:
# Run `gcloud auth application-default login` in your terminal.
# Or, set the GOOGLE_APPLICATION_CREDENTIALS environment variable
# to the path of a service account key file.
list_all_assets(project_id)