Google Cloud Asset

4.3.0 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `AssetServiceClient` and use it to list all resources within a specified Google Cloud project. It relies on Application Default Credentials for authentication.

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)

view raw JSON →