Google Cloud Compute Engine Client Library
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
- breaking The `google-cloud-compute` library, along with other Google Cloud Python client libraries, has officially dropped support for Python 2.7 and Python 3.5.
- gotcha Relying on hardcoded API keys or service account key files for authentication in production environments is discouraged and a security risk.
- gotcha Creating a new client instance (e.g., `compute_v1.InstancesClient()`) for every API call can lead to significant performance overhead due to connection establishment.
- gotcha Many API list methods return paginated results. While Google Cloud client libraries automatically handle pagination using iterators, developers might incorrectly try to implement manual pagination, leading to inefficient code or missed results.
- gotcha The library provides both synchronous and asynchronous clients (e.g., `InstancesClient` vs `InstancesAsyncClient`). Mixing synchronous and asynchronous patterns or choosing the wrong client for your workload (e.g., synchronous for high-concurrency I/O-bound tasks) can lead to performance bottlenecks.
- gotcha Due to the large size of `google-cloud-compute` and other Google Cloud Python libraries, code completion in JetBrains IDEs (like PyCharm) may fail.
Install
-
pip install google-cloud-compute
Imports
- InstancesClient
from google.cloud import compute_v1
Quickstart
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.")