Google Cloud Container API Client Library
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.
Common errors
-
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.fixInstall the library using pip: `pip install google-cloud-container` -
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.fixGrant 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. -
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.fixEnsure 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.
Warnings
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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`.
Install
-
pip install google-cloud-container
Imports
- ContainerServiceClient
from google.cloud.container import ClusterManagerClient
from google.cloud.container_v1 import ContainerServiceClient
Quickstart
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)