Management of source code builds for Cloud Run deployments. Builds compile source code into container images that can be deployed to services and jobs.
Create and configure build clients for managing source builds.
class BuildsClient:
"""Synchronous client for managing Cloud Run builds."""
def __init__(self, *, credentials=None, transport=None, client_options=None, client_info=None):
"""
Initialize the Builds 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 BuildsAsyncClient:
"""Asynchronous client for managing Cloud Run builds."""Submit source code for building into container images.
def submit_build(
self,
request: SubmitBuildRequest = None,
*,
parent: str = None,
storage_source: StorageSource = None,
image_uri: str = None,
**kwargs
) -> Operation:
"""
Submit a build from source code.
Args:
request: The request object containing all parameters
parent: Required. The location to submit the build. Format: projects/{project}/locations/{location}
storage_source: Required. The source code location in Google Cloud Storage
image_uri: Required. The URI of the image to build
Returns:
Operation: Long-running operation that resolves to SubmitBuildResponse
"""Usage Example:
from google.cloud import run_v2
client = run_v2.BuildsClient()
# Define source location
storage_source = run_v2.StorageSource(
bucket="my-source-bucket",
object="source-archive.tar.gz",
generation="12345"
)
# Submit build
request = run_v2.SubmitBuildRequest(
parent="projects/my-project/locations/us-central1",
storage_source=storage_source,
image_uri="gcr.io/my-project/my-app:latest"
)
operation = client.submit_build(request=request)
print("Build submitted, waiting for completion...")
response = operation.result(timeout=1800) # 30 minute timeout
print(f"Build completed: {response.image_uri}")
print(f"Build URI: {response.build_uri}")class StorageSource:
"""
Location of source code in Google Cloud Storage.
Attributes:
bucket (str): Required. Google Cloud Storage bucket containing source
object (str): Required. Google Cloud Storage object containing source
generation (str): Optional. Google Cloud Storage generation for the object
"""class SubmitBuildRequest:
"""
Request message for submitting a build.
Attributes:
parent (str): Required. The location to submit the build
storage_source (StorageSource): Required. The source code location
image_uri (str): Required. The URI where the built image will be stored
build_config (BuildConfig): Optional. Build configuration options
worker_pool (str): Optional. Worker pool to use for the build
validate_only (bool): Indicates whether to validate only
"""class SubmitBuildResponse:
"""
Response message for build submission.
Attributes:
image_uri (str): The URI of the built container image
build_uri (str): The URI of the Cloud Build that was created
base_image_uri (str): The base image used for the build
base_image_warning (str): Warning about the base image if any
"""class BuildConfig:
"""
Configuration for build process.
Attributes:
runtime (str): The runtime to use for the build
source_format (SourceFormat): Format of the source code
dockerfile_path (str): Path to Dockerfile if using custom build
build_args (dict): Build arguments to pass to the build process
environment_variables (dict): Environment variables for the build
worker_pool_options (WorkerPoolOptions): Worker pool configuration
"""def build_from_source(project_id, location, source_bucket, source_object, image_name):
"""
Build a container image from source code.
Args:
project_id: Google Cloud project ID
location: Cloud Run location
source_bucket: GCS bucket containing source
source_object: GCS object with source archive
image_name: Name for the resulting container image
Returns:
Built image URI
"""
client = run_v2.BuildsClient()
# Configure source location
storage_source = run_v2.StorageSource(
bucket=source_bucket,
object=source_object
)
# Build image URI
image_uri = f"gcr.io/{project_id}/{image_name}:latest"
# Submit build
request = run_v2.SubmitBuildRequest(
parent=f"projects/{project_id}/locations/{location}",
storage_source=storage_source,
image_uri=image_uri
)
operation = client.submit_build(request=request)
# Wait for build completion
print("Building container image...")
response = operation.result(timeout=1800)
print(f"Build successful: {response.image_uri}")
return response.image_uri
# Usage
image_uri = build_from_source(
project_id="my-project",
location="us-central1",
source_bucket="my-source-bucket",
source_object="app-v1.2.3.tar.gz",
image_name="my-web-app"
)def build_with_dockerfile(project_id, location, source_location, dockerfile_path, image_uri):
"""
Build using a custom Dockerfile.
"""
client = run_v2.BuildsClient()
# Configure build with custom Dockerfile
build_config = run_v2.BuildConfig(
dockerfile_path=dockerfile_path,
build_args={
"NODE_ENV": "production",
"BUILD_VERSION": "1.2.3"
},
environment_variables={
"BUILDPACK_DISABLE": "true" # Use Dockerfile instead of buildpacks
}
)
request = run_v2.SubmitBuildRequest(
parent=f"projects/{project_id}/locations/{location}",
storage_source=source_location,
image_uri=image_uri,
build_config=build_config
)
operation = client.submit_build(request=request)
response = operation.result()
return responsedef build_with_worker_pool(project_id, location, source_location, image_uri, worker_pool_name):
"""
Build using a custom worker pool for enhanced security or performance.
"""
client = run_v2.BuildsClient()
request = run_v2.SubmitBuildRequest(
parent=f"projects/{project_id}/locations/{location}",
storage_source=source_location,
image_uri=image_uri,
worker_pool=f"projects/{project_id}/locations/{location}/workerPools/{worker_pool_name}"
)
operation = client.submit_build(request=request)
response = operation.result()
print(f"Build completed using worker pool: {worker_pool_name}")
return responsedef monitor_build_progress(operation):
"""
Monitor build progress with periodic status updates.
"""
import time
print("Build started...")
while not operation.done():
print(" Build in progress...")
time.sleep(30) # Check every 30 seconds
# Get operation metadata if available
if hasattr(operation, 'metadata'):
metadata = operation.metadata
if hasattr(metadata, 'progress_percent'):
print(f" Progress: {metadata.progress_percent}%")
if operation.exception():
print(f"Build failed: {operation.exception()}")
return None
else:
result = operation.result()
print(f"Build completed successfully: {result.image_uri}")
return result