Google Cloud Service Usage
The `google-cloud-service-usage` library provides a Python client for the Google Cloud Service Usage API. It enables programmatic management of Google Cloud services within your projects, including listing available services, checking their status, and enabling or disabling them. Part of the `google-cloud-python` monorepo, it is currently at version 1.16.0. Releases for this library, like others in the monorepo, occur frequently, often several times a month, reflecting updates to the underlying API or client code.
Common errors
-
google.api_core.exceptions.PermissionDenied: 403 Permission 'serviceusage.services.list' denied on resource 'projects/your-gcp-project-id'.
cause The authenticated principal (user or service account) does not have the necessary IAM permissions to perform the requested action on the specified project.fixGrant the `Service Usage Consumer` role (for listing) or `Service Usage Admin` role (for enabling/disabling) to the principal via the Google Cloud Console IAM page or `gcloud iam roles` commands. -
AttributeError: module 'google.cloud' has no attribute 'service_usage'
cause The Python import statement is attempting to access a module that does not exist directly under `google.cloud`. Google Cloud client libraries typically place the client in a versioned submodule.fixCorrect the import statement to `from google.cloud import service_usage_v1` and then instantiate `client = service_usage_v1.ServiceUsageClient()`. -
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or provide a Google Cloud project ID.
cause The Python client library could not find any default credentials to authenticate with Google Cloud. This usually means `GOOGLE_APPLICATION_CREDENTIALS` is not set or `gcloud auth application-default login` hasn't been run.fixFor local development, run `gcloud auth application-default login`. For production, ensure the `GOOGLE_APPLICATION_CREDENTIALS` environment variable points to a valid service account key file path. -
google.api_core.exceptions.NotFound: 404 Service not found: services/invalid.service.name
cause The service name provided in the request (e.g., to `enable_service` or `get_service`) is incorrect or refers to a service that does not exist or is not associated with the project.fixVerify the exact service name (e.g., `compute.googleapis.com`, `storage.googleapis.com`) using the Google Cloud Console Service Usage page or by programmatically listing available services.
Warnings
- gotcha Google Cloud client libraries require proper authentication. If running locally, `gcloud auth application-default login` is often necessary. In deployed environments, consider Service Accounts or Workload Identity.
- gotcha Interacting with Google Cloud services requires specific IAM permissions. Common errors include 'Permission Denied'.
- gotcha Resource names for Google Cloud APIs often follow a strict format (e.g., `projects/PROJECT_ID`, `services/SERVICE_NAME`). Incorrect formatting or IDs will lead to 'Not Found' errors.
- gotcha Operations like `enable_service` and `disable_service` return a `google.api_core.operation.Operation` object, not the final result. These are long-running operations.
Install
-
pip install google-cloud-service-usage
Imports
- ServiceUsageClient
from google.cloud import service_usage
from google.cloud import service_usage_v1
Quickstart
import os
from google.cloud import service_usage_v1
# Set your Google Cloud Project ID
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "your-gcp-project-id") # Replace with a valid project ID
# IMPORTANT: Ensure you have authenticated to GCP.
# For local development, run `gcloud auth application-default login`.
# For service accounts, set the GOOGLE_APPLICATION_CREDENTIALS environment variable.
try:
# Initialize the Service Usage client
client = service_usage_v1.ServiceUsageClient()
# Construct the parent resource name
parent = f"projects/{project_id}"
print(f"Listing enabled services for project: {project_id}")
# Create a request to list services, filtered by enabled state
request = service_usage_v1.ListServicesRequest(
parent=parent,
filter="state:ENABLED"
)
# Make the API call
response = client.list_services(request=request)
enabled_services = [service.config.name for service in response.services]
if enabled_services:
print(f"Enabled services found ({len(enabled_services)}):")
for service_name in enabled_services[:5]: # Print first 5 for brevity
print(f"- {service_name}")
if len(enabled_services) > 5:
print(f"... and {len(enabled_services) - 5} more.")
else:
print("No enabled services found for this project or insufficient permissions.")
except Exception as e:
print(f"An error occurred: {e}")
print("Please ensure:")
print("1. Your project ID is correct.")
print("2. You are authenticated (e.g., `gcloud auth application-default login`).")
print("3. The authenticated principal has the 'Service Usage Consumer' IAM role or equivalent.")