Google Cloud Container API Client Library

2.63.0 · active · verified Sun Mar 29

The `google-cloud-container` Python client library provides programmatic access to the Google Kubernetes Engine (GKE) API. It allows developers to build and manage container-based applications using the open-source Kubernetes technology. The current version is 2.63.0, and it follows a frequent release cadence as part of the broader `google-cloud-python` monorepo.

Warnings

Install

Imports

Quickstart

Initializes the Google Kubernetes Engine client and lists all clusters within a specified Google Cloud project and location (zone/region), demonstrating basic connectivity and resource retrieval. Authentication is handled automatically via Application Default Credentials (ADC) from the environment or `gcloud` CLI.

import os
from google.cloud.container_v1 import ContainerServiceClient
from google.api_core.exceptions import GoogleAPIError

def list_gke_clusters(project_id: str, location: str = "-"):
    """Lists all Google Kubernetes Engine clusters in a given project and location.

    Args:
        project_id: Your Google Cloud project ID.
        location: The Google Cloud location (e.g., "us-central1" for a region,
                  or "us-central1-a" for a zone). Use "-" for all locations.
    """
    try:
        client = ContainerServiceClient()
        parent = f"projects/{project_id}/locations/{location}"
        
        # The list_clusters method is paginated, iterate through the responses
        response = client.list_clusters(parent=parent)
        
        if response.clusters:
            print(f"Clusters in project '{project_id}' and location '{location}':")
            for cluster in response.clusters:
                print(f"- Name: {cluster.name}")
                print(f"  Location: {cluster.location}")
                print(f"  Status: {cluster.status.name}")
                print(f"  Endpoint: {cluster.endpoint}")
        else:
            print(f"No clusters found in project '{project_id}' and location '{location}'.")

    except GoogleAPIError as e:
        print(f"An API error occurred: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    # Set your Google Cloud Project ID as an environment variable
    # For local development, ensure GOOGLE_APPLICATION_CREDENTIALS is set
    # or you've run `gcloud auth application-default login`
    project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "your-gcp-project-id")
    
    # Optionally specify a specific region or zone, e.g., "us-central1" or "us-central1-a"
    # Use "-" to list clusters across all regions/zones
    target_location = os.environ.get("GKE_LOCATION", "-")

    if project_id == "your-gcp-project-id":
        print("Please set the 'GOOGLE_CLOUD_PROJECT' environment variable to your project ID.")
        print("For example: export GOOGLE_CLOUD_PROJECT='my-project-123'")
    else:
        list_gke_clusters(project_id, target_location)

view raw JSON →