Google Cloud Container API Client Library

raw JSON →
2.63.0 verified Tue May 12 auth: no python install: stale

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.

pip install google-cloud-container
error ModuleNotFoundError: No module named 'google.cloud.container_v1'
cause The `google-cloud-container` Python client library, or a dependency, is not installed in the active Python environment.
fix
Install the library using pip: pip install google-cloud-container
error ERROR: (gcloud.container.clusters.get-credentials) ResponseError: code=403, message=Required "container.clusters.get" permission(s)
cause The authenticated Google Cloud user or service account lacks the necessary IAM permissions to access or retrieve credentials for the specified GKE cluster.
fix
Grant the 'Kubernetes Engine Cluster Viewer' role (roles/container.viewer) or a more permissive role (like 'Kubernetes Engine Developer' or 'Owner') to the user or service account on the Google Cloud project or specific cluster.
error Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable.
cause The application inside the deployed container (e.g., on GKE or Cloud Run) did not start a web server or an I/O-bound application that listens on the port specified by the `PORT` environment variable (default 8080) or failed its startup health checks.
fix
Ensure your application is configured to listen on 0.0.0.0:$PORT (where $PORT is the environment variable Cloud Run/GKE provides) and that it starts successfully and responds to health checks within the configured timeout. Inspect container logs for application-specific errors.
gotcha Always use Application Default Credentials (ADC) for authentication. Avoid hardcoding service account key files, embedding them in Docker images, or committing them to source control. For local development, use `gcloud auth application-default login`. For deployed services, rely on attached service accounts or Workload Identity.
fix Configure ADC properly for your environment. Use environment variables like `GOOGLE_APPLICATION_CREDENTIALS` only when absolutely necessary (e.g., CI/CD outside GCP with temporary keys), and ensure they are securely managed.
gotcha When interacting with GKE regional clusters, the `get_cluster` or `list_clusters` methods require specifying the `name` or `parent` field with the region, not the `zone` field. Using `zone` for a regional cluster will result in an `InvalidArgument` error.
fix For regional clusters, construct the `parent` parameter as `projects/{project_id}/locations/{region}`. For example, `client.list_clusters(parent='projects/my-project/locations/us-central1')`.
breaking The `google-cloud-container` library, like other `google-cloud-python` libraries, no longer supports Python versions older than 3.7. Attempting to use it with Python 3.6 or earlier will lead to installation or runtime errors.
fix Upgrade your Python environment to version 3.7 or newer. Python 3.7 is the minimum requirement, but generally, it's recommended to use actively maintained Python versions.
gotcha The logging events from this library (and other `google-cloud-python` libraries) are subject to change. Google may refine the occurrence, level, and content of various log messages without flagging these changes as breaking. Do not depend on the immutability of specific logging events for application logic.
fix While logging can be useful for debugging, avoid building critical application logic that relies on the exact format or content of log messages from the client library. Implement robust error handling based on API responses and exceptions.
deprecated It is not recommended to install the monolithic `google-api-python-client` package if you only need specific Google Cloud services. This approach leads to larger distribution sizes and can complicate dependency management.
fix Install only the specific `google-cloud-*` client libraries your application requires, such as `google-cloud-container` for GKE interactions.
breaking Python 3.9 has reached its end-of-life and is no longer actively supported by `google-cloud-container` and its core dependencies (`google.api_core`, `google.auth`). Using the library with Python 3.9 will result in `FutureWarning` messages regarding unsupported Python versions and can lead to critical runtime errors, such as `ImportError`, preventing the library from functioning correctly.
fix Upgrade your Python environment to an actively supported version. Google recommends Python 3.10 or newer.
breaking The `ContainerServiceClient` class is no longer directly importable from `google.cloud.container_v1`. This class has been renamed to `ClusterManagerClient` and is typically imported from `google.cloud.container` or `google.cloud.container_v1.services.cluster_manager`.
fix Update your import statement. For example, replace `from google.cloud.container_v1 import ContainerServiceClient` with `from google.cloud.container import ClusterManagerClient` or `from google.cloud.container_v1.services.cluster_manager import ClusterManagerClient`, and adjust subsequent code accordingly.
python os / libc status wheel install import disk
3.10 alpine (musl) wheel - - 72.4M
3.10 alpine (musl) - - - -
3.10 slim (glibc) wheel 6.1s - 70M
3.10 slim (glibc) - - - -
3.11 alpine (musl) wheel - - 77.5M
3.11 alpine (musl) - - - -
3.11 slim (glibc) wheel 5.2s - 75M
3.11 slim (glibc) - - - -
3.12 alpine (musl) wheel - - 68.9M
3.12 alpine (musl) - - - -
3.12 slim (glibc) wheel 4.3s - 67M
3.12 slim (glibc) - - - -
3.13 alpine (musl) wheel - - 68.5M
3.13 alpine (musl) - - - -
3.13 slim (glibc) wheel 4.5s - 66M
3.13 slim (glibc) - - - -
3.9 alpine (musl) wheel - - 72.5M
3.9 alpine (musl) - - - -
3.9 slim (glibc) wheel 6.8s - 70M
3.9 slim (glibc) - - - -

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)