Comprehensive management of Cloud Run services, including creation, configuration, traffic routing, scaling, and lifecycle management. Services are stateless HTTP applications that automatically scale to handle incoming requests.
Create and configure service clients with authentication and regional endpoints.
class ServicesClient:
"""Synchronous client for managing Cloud Run services."""
def __init__(self, *, credentials=None, transport=None, client_options=None, client_info=None):
"""
Initialize the Services client.
Args:
credentials: Optional authentication credentials
transport: Transport to use for requests (grpc, grpc_asyncio, rest)
client_options: Client configuration options
client_info: Client information for user agent
"""
class ServicesAsyncClient:
"""Asynchronous client for managing Cloud Run services."""
def __init__(self, *, credentials=None, transport=None, client_options=None, client_info=None):
"""Initialize the async Services client with the same parameters."""Create new Cloud Run services with container specifications, resource requirements, and configuration.
def create_service(
self,
request: CreateServiceRequest = None,
*,
parent: str = None,
service: Service = None,
service_id: str = None,
**kwargs
) -> Operation:
"""
Create a new Cloud Run service.
Args:
request: The request object containing all parameters
parent: Required. The location to create the service. Format: projects/{project}/locations/{location}
service: Required. The service configuration
service_id: Required. The unique identifier for the service
Returns:
Operation: Long-running operation that resolves to the created Service
"""Usage Example:
from google.cloud import run_v2
client = run_v2.ServicesClient()
# Define service configuration
service = run_v2.Service()
service.template.containers = [
run_v2.Container(
image="gcr.io/my-project/my-app:latest",
ports=[run_v2.ContainerPort(container_port=8080)],
resources=run_v2.ResourceRequirements(
limits={"cpu": "1", "memory": "512Mi"}
),
env=[
run_v2.EnvVar(name="NODE_ENV", value="production")
]
)
]
# Configure scaling
service.template.scaling = run_v2.RevisionScaling(
min_instance_count=0,
max_instance_count=10
)
# Create the service
request = run_v2.CreateServiceRequest(
parent="projects/my-project/locations/us-central1",
service=service,
service_id="my-web-app"
)
operation = client.create_service(request=request)
service_response = operation.result()
print(f"Service created: {service_response.name}")Get service details and status information.
def get_service(
self,
request: GetServiceRequest = None,
*,
name: str = None,
**kwargs
) -> Service:
"""
Get a Cloud Run service.
Args:
request: The request object
name: Required. The name of the service. Format: projects/{project}/locations/{location}/services/{service}
Returns:
Service: The service configuration and status
"""List services with filtering and pagination.
def list_services(
self,
request: ListServicesRequest = None,
*,
parent: str = None,
**kwargs
) -> ListServicesResponse:
"""
List Cloud Run services in a location.
Args:
request: The request object
parent: Required. The location to list services. Format: projects/{project}/locations/{location}
Returns:
ListServicesResponse: Paginated list of services
"""Usage Example:
# List all services in a location
request = run_v2.ListServicesRequest(
parent="projects/my-project/locations/us-central1"
)
page_result = client.list_services(request=request)
for service in page_result:
print(f"Service: {service.name}, Status: {service.status.condition}")Update service configuration, container images, environment variables, and scaling settings.
def update_service(
self,
request: UpdateServiceRequest = None,
*,
service: Service = None,
**kwargs
) -> Operation:
"""
Update a Cloud Run service.
Args:
request: The request object
service: Required. The service configuration to update
Returns:
Operation: Long-running operation that resolves to the updated Service
"""Usage Example:
# Get existing service
service = client.get_service(name="projects/my-project/locations/us-central1/services/my-app")
# Update container image
service.template.containers[0].image = "gcr.io/my-project/my-app:v2"
# Update scaling
service.template.scaling.max_instance_count = 20
# Apply update
request = run_v2.UpdateServiceRequest(service=service)
operation = client.update_service(request=request)
updated_service = operation.result()Delete services and clean up associated resources.
def delete_service(
self,
request: DeleteServiceRequest = None,
*,
name: str = None,
**kwargs
) -> Operation:
"""
Delete a Cloud Run service.
Args:
request: The request object
name: Required. The name of the service to delete
Returns:
Operation: Long-running operation for the deletion
"""Manage Identity and Access Management policies for services.
def get_iam_policy(
self,
request,
*,
resource: str = None,
**kwargs
):
"""Get the IAM access control policy for a service."""
def set_iam_policy(
self,
request,
*,
resource: str = None,
policy = None,
**kwargs
):
"""Set the IAM access control policy for a service."""
def test_iam_permissions(
self,
request,
*,
resource: str = None,
permissions: list[str] = None,
**kwargs
):
"""Test IAM permissions for a service."""class Service:
"""
A Cloud Run service configuration.
Attributes:
name (str): The unique name of the service
uid (str): Unique identifier assigned by the system
generation (int): A sequence number representing a specific generation
labels (dict): User-defined labels
annotations (dict): User-defined annotations
create_time (Timestamp): The creation time
update_time (Timestamp): The last modification time
delete_time (Timestamp): The deletion time
expire_time (Timestamp): When the service expires
creator (str): Email address of the user who created the service
last_modifier (str): Email address of the last user to modify the service
client (str): Arbitrary identifier for the client
client_version (str): Version identifier for the client
ingress (IngressTraffic): Ingress settings for the service
launch_stage (LaunchStage): The launch stage of the service
binary_authorization (BinaryAuthorization): Binary authorization policy
template (RevisionTemplate): The template describing the service revision
traffic (list[TrafficTarget]): Traffic allocation configuration
scaling (ServiceScaling): Scaling configuration for the service
default_uri_disabled (bool): Whether the default URI is disabled
observed_generation (int): The generation observed by the controller
terminal_condition (Condition): The terminal condition of the service
conditions (list[Condition]): Detailed status conditions
latest_ready_revision (str): Name of the latest ready revision
latest_created_revision (str): Name of the latest created revision
traffic_statuses (list[TrafficTargetStatus]): Traffic status for each target
uri (str): The main URI where the service is accessible
custom_audiences (list[str]): Custom audiences for JWT tokens
satisfies_pzs (bool): Whether the service satisfies PZS requirements
reconciling (bool): Whether the service is currently being reconciled
etag (str): A fingerprint used for optimistic concurrency control
"""class CreateServiceRequest:
"""
Request message for creating a service.
Attributes:
parent (str): Required. The location to create the service
service (Service): Required. The service configuration
service_id (str): Required. The unique identifier for the service
validate_only (bool): Indicates whether to validate only
"""
class GetServiceRequest:
"""
Request message for getting a service.
Attributes:
name (str): Required. The name of the service to retrieve
"""
class ListServicesRequest:
"""
Request message for listing services.
Attributes:
parent (str): Required. The location to list services in
page_size (int): Maximum number of services to return
page_token (str): Token for retrieving the next page
show_deleted (bool): Whether to include deleted services
"""
class UpdateServiceRequest:
"""
Request message for updating a service.
Attributes:
service (Service): Required. The service configuration to update
validate_only (bool): Indicates whether to validate only
allow_missing (bool): Whether to allow creation if service doesn't exist
"""
class DeleteServiceRequest:
"""
Request message for deleting a service.
Attributes:
name (str): Required. The name of the service to delete
validate_only (bool): Indicates whether to validate only
etag (str): A fingerprint for optimistic concurrency control
"""class ListServicesResponse:
"""
Response message for listing services.
Attributes:
services (list[Service]): The list of services
next_page_token (str): Token for retrieving the next page
"""from google.api_core import exceptions
try:
service = client.get_service(name="projects/my-project/locations/us-central1/services/my-app")
except exceptions.NotFound:
print("Service not found")
except exceptions.PermissionDenied:
print("Insufficient permissions to access service")# Create service and wait for completion
operation = client.create_service(request=create_request)
print("Creating service...")
# Wait for operation to complete
result = operation.result(timeout=300) # 5 minute timeout
print(f"Service created: {result.name}")
# Check operation status without blocking
if not operation.done():
print("Operation still in progress...")# Use helper methods for resource paths
service_name = client.service_path("my-project", "us-central1", "my-service")
parent_path = client.location_path("my-project", "us-central1")
# Parse resource names
parsed = client.parse_service_path(service_name)
print(f"Project: {parsed['project']}, Location: {parsed['location']}, Service: {parsed['service']}")