Google Cloud Compute Engine Client Library

1.46.0 · active · verified Sat Mar 28

The `google-cloud-compute` Python client library provides programmatic access to Google Cloud Compute Engine, which delivers virtual machines running in Google's innovative data centers and worldwide fiber network. It allows developers to manage VM instances, disks, networks, and other Compute Engine resources. The library is actively maintained by Google and receives frequent updates, with the current version being 1.46.0.

Warnings

Install

Imports

Quickstart

This quickstart code demonstrates how to authenticate and list all virtual machine instances within a specified Google Cloud project. It uses Application Default Credentials (ADC) for authentication, which is the recommended method. Replace `your-gcp-project-id` or set the `GCP_PROJECT_ID` environment variable.

import google.cloud.compute_v1 as compute_v1
import os

def list_all_instances(project_id: str) -> None:
    """Lists all instances across all zones in the given project."""
    client = compute_v1.InstancesClient()
    # aggregated_list returns instances grouped by zone
    aggregated_list = client.aggregated_list(project=project_id)

    print(f"Instances in project {project_id}:")
    for zone, scope in aggregated_list.items():
        if scope.instances:
            print(f"  Zone: {zone}")
            for instance in scope.instances:
                print(f"    - {instance.name} ({instance.status})")

# Replace with your Google Cloud Project ID or set as an environment variable
PROJECT_ID = os.environ.get('GCP_PROJECT_ID', 'your-gcp-project-id')

if PROJECT_ID == 'your-gcp-project-id':
    print("WARNING: Please set the 'GCP_PROJECT_ID' environment variable or replace 'your-gcp-project-id' in the code.")
else:
    try:
        list_all_instances(PROJECT_ID)
    except Exception as e:
        print(f"An error occurred: {e}")
        print("Ensure the Compute Engine API is enabled for your project and your credentials are set up correctly.")

view raw JSON →