Kanji
・Cloud engineer / freelance ・Born in 1993 ・From Ehime / Living in Shibuya, Tokyo ・5 years AWS experience Profile details
Table of Contents
options.logging: CLOUD_LOGGING_ONLY
apt install jq
keepCount: 10
UNTAGGED
asia-northeast1
$0.00/GiB
--no-traffic --tag
cloudbuild.yaml
Back in June 2022, I published a short cloudbuild.yaml snippet here as my personal reference template: parameterize CPU/memory with substitutions , build and push a Docker image to Artifact Registry, deploy to Cloud Run, and run a small jq loop at the end to delete older images.
substitutions
jq
When I copied that exact cloudbuild.yaml into a newly provisioned Google Cloud project a while later, the pipeline failed before Step 1 even started—and revisiting the script exposed two deeper operational flaws that had been lurking in my 2022 setup:
First, the build immediately errored out with generic::invalid_argument: if 'build.service_account' is specified, the build must either (a) specify 'build.logs_bucket' ... or (c) use either CLOUD_LOGGING_ONLY / NONE logging options . Google Cloud moved away from relying on the legacy, overly permissive Cloud Build service account ( PROJECT_NUMBER@cloudbuild.gserviceaccount.com ) in favor of user-managed custom service accounts. Because a custom service account cannot write to Google’s internal default GCS log bucket, omitting options.logging: CLOUD_LOGGING_ONLY causes every trigger run to fail at validation time.
generic::invalid_argument: if 'build.service_account' is specified, the build must either (a) specify 'build.logs_bucket' ... or (c) use either CLOUD_LOGGING_ONLY / NONE logging options
PROJECT_NUMBER@cloudbuild.gserviceaccount.com
Second, Step ④ in my 2022 YAML installed jq via apt -y install jq on every single build and deleted all Artifact Registry digests older than 5 minutes ago . At the time, Artifact Registry lacked built-in lifecycle management. In practice, that shell snippet burned ~30 seconds of build time on every commit and wiped out the container image backing the previous production Cloud Run revision. During one bad deployment, I tried rolling traffic back to the prior revision only to discover its underlying image digest had already been purged five minutes after the previous release. Today, Artifact Registry provides native Cleanup Policies (GA), making in-build deletion scripts both unnecessary and dangerous.
apt -y install jq
5 minutes ago
Third, my 2022 note warned against --cache-from out of fear of outbound data transfer charges. Looking back, those egress charges happened because my Cloud Build trigger had been created as a global trigger (spinning up default workers in US regions) while pulling and pushing against an asia-northeast1 (Tokyo) Artifact Registry repository. When you pin the Cloud Build trigger itself to --region=asia-northeast1 , intra-region data transfer between Cloud Build and Artifact Registry is $0.00/GiB , and the default e2-standard-2 worker pool still qualifies for the 2,500 free build-minutes per month allowance.
--cache-from
global
--region=asia-northeast1
e2-standard-2
Below is the completely rewritten 2026 production pipeline incorporating least-privilege IAM separation, same-region BuildKit caching, --no-traffic canary verification, and native Artifact Registry Cleanup Policies.
--no-traffic
▲ Single-region (asia-northeast1) production CI/CD architecture combining least-privilege SA separation, BuildKit caching, Artifact Registry Cleanup Policies, and zero-downtime Cloud Run traffic shifting
Before diving into the YAML and CLI commands, here is how each design decision changed between 2022 and 2026. Note that Google Container Registry ( *.gcr.io ) for user images has been completely shut down, so all application images must target Artifact Registry ( *-docker.pkg.dev ). Official Cloud Build builder images such as gcr.io/cloud-builders/docker remain supported because Google hosts them on Artifact Registry behind the scenes.
*.gcr.io
*-docker.pkg.dev
gcr.io/cloud-builders/docker
--cache-from :cache
gcloud run deploy
--no-traffic --tag=canary
/healthz
update-traffic
The first rule of a hardened Cloud Run pipeline is separating who deploys the container (Build SA) from what the container can access at runtime (Runtime SA) . If both share the same identity, a compromised web container could query the metadata server and abuse run.admin or artifactregistry.writer permissions.
run.admin
artifactregistry.writer
The commands below create two dedicated service accounts and bind roles/iam.serviceAccountUser only on the run-app-sa resource itself — never at the project level — so cb-deployer can attach run-app-sa to Cloud Run without being able to impersonate any other privileged service account in the project.
roles/iam.serviceAccountUser
run-app-sa
cb-deployer
PROJECT_ID="your-gcp-project-id" REGION="asia-northeast1" REPO_NAME="app-containers" # 1. Runtime Service Account for Cloud Run (grant only app-specific DB/Secret permissions, zero deploy rights) gcloud iam service-accounts create run-app-sa \ --display-name="Cloud Run Runtime Service Account" \ --project="${PROJECT_ID}" # 2. Dedicated Deployer Service Account for Cloud Build gcloud iam service-accounts create cb-deployer \ --display-name="Cloud Build Deployer Service Account" \ --project="${PROJECT_ID}" CB_SA="cb-deployer@${PROJECT_ID}.iam.gserviceaccount.com" RUN_SA="run-app-sa@${PROJECT_ID}.iam.gserviceaccount.com" # 3. Grant minimal project-level roles to Build SA for ROLE in \ roles/artifactregistry.writer \ roles/run.admin \ roles/logging.logWriter; do gcloud projects add-iam-policy-binding "${PROJECT_ID}" \ --member="serviceAccount:${CB_SA}" \ --role="${ROLE}" done # 4. Critical: Scope roles/iam.serviceAccountUser strictly to the Runtime SA resource, NOT the project gcloud iam service-accounts add-iam-policy-binding "${RUN_SA}" \ --member="serviceAccount:${CB_SA}" \ --role="roles/iam.serviceAccountUser" \ --project="${PROJECT_ID}"
Once cb-deployer is attached to your Cloud Build trigger and roles/logging.logWriter is granted, adding options.logging: CLOUD_LOGGING_ONLY to cloudbuild.yaml resolves the custom service account validation error cleanly.
roles/logging.logWriter
Here is the updated cloudbuild.yaml I use today. It introduces three structural improvements over the 2022 version:
:$COMMIT_SHA
:cache
DOCKER_BUILDKIT=1
BUILDKIT_INLINE_CACHE=1
0%
canary---*.run.app
gcloud auth print-identity-token
--no-allow-unauthenticated
100%
# cloudbuild.yaml (Same-region asia-northeast1, Custom SA, BuildKit cache, zero-downtime traffic shift) substitutions: _REGION: "asia-northeast1" _REPO_NAME: "app-containers" _SERVICE_NAME: "order-api" _RUNTIME_SA: "run-app-sa@${PROJECT_ID}.iam.gserviceaccount.com" _CPU: "1" _MEMORY: "512Mi" _MIN_INSTANCES: "0" _MAX_INSTANCES: "10" options: # Mandatory when running Cloud Build with a user-managed custom Service Account logging: CLOUD_LOGGING_ONLY machineType: E2_HIGHCPU_8 # Omit this line to stay on e2-standard-2 (2,500 free build-min/month) steps: # 1. Pull previous :cache image (tolerate missing tag on very first build via || exit 0) - id: "pull-cache" name: "gcr.io/cloud-builders/docker" entrypoint: "bash" args: - "-c" - | docker pull ${_REGION}-docker.pkg.dev/${PROJECT_ID}/${_REPO_NAME}/${_SERVICE_NAME}:cache || exit 0 # 2. Build with Docker BuildKit layer caching, tagging both immutable COMMIT_SHA and :cache - id: "build-image" name: "gcr.io/cloud-builders/docker" env: - "DOCKER_BUILDKIT=1" args: - "build" - "--build-arg" - "BUILDKIT_INLINE_CACHE=1" - "--cache-from" - "${_REGION}-docker.pkg.dev/${PROJECT_ID}/${_REPO_NAME}/${_SERVICE_NAME}:cache" - "-t" - "${_REGION}-docker.pkg.dev/${PROJECT_ID}/${_REPO_NAME}/${_SERVICE_NAME}:${COMMIT_SHA}" - "-t" - "${_REGION}-docker.pkg.dev/${PROJECT_ID}/${_REPO_NAME}/${_SERVICE_NAME}:cache" - "." # 3. Push both tags to same-region Artifact Registry ($0.00/GiB intra-region transfer) - id: "push-image" name: "gcr.io/cloud-builders/docker" args: - "push" - "--all-tags" - "${_REGION}-docker.pkg.dev/${PROJECT_ID}/${_REPO_NAME}/${_SERVICE_NAME}" # 4. Deploy new Cloud Run revision with 0% live traffic (--no-traffic) and a dedicated 'canary' tag URL - id: "deploy-no-traffic" name: "gcr.io/google.com/cloudsdktool/cloud-sdk:slim" entrypoint: "gcloud" args: - "run" - "deploy" - "${_SERVICE_NAME}" - "--image=${_REGION}-docker.pkg.dev/${PROJECT_ID}/${_REPO_NAME}/${_SERVICE_NAME}:${COMMIT_SHA}" - "--region=${_REGION}" - "--service-account=${_RUNTIME_SA}" - "--cpu=${_CPU}" - "--memory=${_MEMORY}" - "--min-instances=${_MIN_INSTANCES}" - "--max-instances=${_MAX_INSTANCES}" - "--no-traffic" - "--tag=canary" # 5. Run authenticated smoke test against canary URL; shift 100% traffic only on HTTP 200 - id: "smoke-test-and-promote" name: "gcr.io/google.com/cloudsdktool/cloud-sdk:slim" entrypoint: "bash" args: - "-euo" - "pipefail" - "-c" - | CANARY_URL=$(gcloud run services describe "${_SERVICE_NAME}" \ --region="${_REGION}" \ --format="value(status.traffic.filter(tag:canary).url)") TOKEN=$(gcloud auth print-identity-token) echo "Verifying canary endpoint: $${CANARY_URL}/healthz" HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" \ -H "Authorization: Bearer $${TOKEN}" \ "$${CANARY_URL}/healthz") if [ "$${HTTP_STATUS}" != "200" ]; then echo "Smoke test failed with HTTP $${HTTP_STATUS}. Aborting traffic shift." exit 1 fi gcloud run services update-traffic "${_SERVICE_NAME}" \ --region="${_REGION}" \ --to-latest images: - "${_REGION}-docker.pkg.dev/${PROJECT_ID}/${_REPO_NAME}/${_SERVICE_NAME}:${COMMIT_SHA}"
One small syntax detail that tripped me up once: inside inline bash blocks in cloudbuild.yaml , always escape bash variables with a double dollar sign ( $${CANARY_URL} , $${HTTP_STATUS} ). A single $ tells Cloud Build to parse it as a build substitution variable, which fails trigger validation with invalid value for 'build.substitutions' .
bash
$${CANARY_URL}
$${HTTP_STATUS}
$
invalid value for 'build.substitutions'
The sequence diagram below illustrates how staged deployment protects live traffic when a container fails startup checks:
Beyond Artifact Registry’s 0.5 GiB monthly free tier, container storage costs roughly $0.10/GiB-month in asia-northeast1 . Left unchecked, frequent CI builds accumulate untagged intermediate manifests and old commit images.
$0.10/GiB-month
Instead of deleting images inside cloudbuild.yaml , attach a repository-level Cleanup Policy JSON combining Delete rules with a Keep rule ( keepCount: 10 ). Because Keep rules always override Delete rules in Artifact Registry, even a low-traffic microservice that hasn’t been deployed in six months is guaranteed to retain its 10 most recent versions for instant Cloud Run rollbacks.
Keep
Delete
[ { "name": "delete-untagged-after-7d", "action": { "type": "Delete" }, "condition": { "tagState": "UNTAGGED", "olderThan": "604800s" } }, { "name": "delete-old-commits-after-30d", "action": { "type": "Delete" }, "condition": { "tagState": "ANY", "olderThan": "2592000s" } }, { "name": "keep-latest-10-versions", "action": { "type": "Keep" }, "mostRecentVersions": { "keepCount": 10 } } ]
Always test your cleanup-policy.json in --dry-run mode first so Artifact Registry logs simulated deletions to Cloud Logging without touching live digests, then enforce it with --no-dry-run :
cleanup-policy.json
--dry-run
--no-dry-run
# 1. Register in dry-run mode first to audit candidate deletions in Cloud Logging gcloud artifacts repositories set-cleanup-policies "${REPO_NAME}" \ --project="${PROJECT_ID}" \ --location="${REGION}" \ --policy=cleanup-policy.json \ --dry-run # 2. Enforce live cleanup once verified gcloud artifacts repositories set-cleanup-policies "${REPO_NAME}" \ --project="${PROJECT_ID}" \ --location="${REGION}" \ --policy=cleanup-policy.json \ --no-dry-run
When creating a Cloud Build trigger via CLI or Terraform, omitting --region creates a global trigger whose default workers may run outside your target region. Always pin --region to match your Artifact Registry location ( asia-northeast1 in this example):
--region
gcloud builds triggers create github \ --name="deploy-order-api-prod" \ --region="asia-northeast1" \ --repository="projects/${PROJECT_ID}/locations/asia-northeast1/connections/github-conn/repositories/order-api" \ --branch-pattern="^main$" \ --build-config="cloudbuild.yaml" \ --service-account="projects/${PROJECT_ID}/serviceAccounts/${CB_SA}"
For personal projects or small internal APIs with a few deployments per day, omit machineType: E2_HIGHCPU_8 from options so builds run on the default e2-standard-2 machine type—which includes 2,500 free build-minutes per billing account per month even in regional default pools like asia-northeast1 . With BuildKit layer caching enabled in the same region, typical FastAPI or Next.js builds finish in 45--70 seconds, keeping monthly Cloud Build compute and network transfer bills at $0.00 .
machineType: E2_HIGHCPU_8
options
$0.00
You might also wonder whether you still need a custom cloudbuild.yaml at all given gcloud run deploy --source . and Cloud Run’s built-in GitHub continuous deployment setup. For single-container tools that don’t need pre-cutover smoke checks or database migrations, I use --source deployments myself. Once a service requires --no-traffic canary gating, Cloud Run Jobs database migrations prior to traffic promotion, or shared layer caching across a monorepo, maintaining an explicit cloudbuild.yaml in Git gives you far cleaner control.
gcloud run deploy --source .
--source
One area I am still evaluating across larger monorepos is docker build ( BUILDKIT_INLINE_CACHE=1 ) versus docker buildx build --cache-to type=registry,mode=max . While mode=max caches intermediate multi-stage build layers that don’t make it into the final runtime image, bootstrapping a buildx container driver on a fresh ephemeral Cloud Build worker adds several seconds of startup overhead on every run—so for smaller services, standard BUILDKIT_INLINE_CACHE=1 often wins on wall-clock time.
docker build
docker buildx build --cache-to type=registry,mode=max
mode=max
buildx
User-managed custom service accounts do not have write access to Google Cloud’s internal default GCS log bucket. Adding options: logging: CLOUD_LOGGING_ONLY in cloudbuild.yaml and granting roles/logging.logWriter to your custom service account routes build logs directly to Cloud Logging without requiring a dedicated Cloud Storage bucket.
options: logging: CLOUD_LOGGING_ONLY
Yes. While *.gcr.io Container Registry for customer-hosted images has been shut down in favor of Artifact Registry ( *-docker.pkg.dev ), Google’s official builder images under gcr.io/cloud-builders/* and gcr.io/google.com/cloudsdktool/* are hosted by Google on Artifact Registry infrastructure and remain officially supported.
gcr.io/cloud-builders/*
gcr.io/google.com/cloudsdktool/*
If you only configure an age-based Delete rule (such as deleting images older than 30 days), a service that hasn’t been redeployed in over a month could lose its active image digest. Pairing your delete rules with a Keep rule ( mostRecentVersions.keepCount: 10 ) prevents this because Keep rules always take precedence over Delete rules, guaranteeing that the 10 newest versions per package remain untouched.
mostRecentVersions.keepCount: 10
Master conversation skills with realistic AI phone training and 5-axis feedback. Includes 16-lesson interactive academy and studio AI portraits.
Effortlessly snap receipts for instant AI itemization. Integrated with LINE for seamless group expense tracking and pain-free settlement.
Interactive AI personas (Fortune Teller, Butler, Bartender) host real-time games, challenges, and conversation starters for unforgettable gatherings.
Real-time AI quant analysis of earnings reports, corporate filings, and momentum indicators for global equities and Japanese stocks.
Unbiased healthcare database featuring zero-additive filters and active ingredient cost performance metrics.
Get the complete configuration pack featured in this article: universal AGENTS.md, deterministic hooks.json, Git safety guardrails, and validation scripts tested across Antigravity, Kiro, Claude Code, and Codex.