Loading
Portfolio
Rayden Li
CI/CD · Google Cloud Platform · Docker
This guide builds a Docker image with Cloud Build, stores it in Artifact Registry, and deploys it to a private Cloud Run service. The example uses separate identities, repository-scoped access where possible, immutable image tags, and no downloaded service-account keys.
The commands are a template. Run them from an administrator-controlled terminal only after replacing the example names. Test the design in a non-production project first.
A CI/CD pipeline handles source code and also holds permission to change production. Assume that a malicious commit, compromised dependency, untrusted pull request, or careless operator might try to:
Cloud Build triggers make repository access security-sensitive: someone who can change code selected by a trigger can cause that code to run with the trigger's build-time permissions. Google explicitly documents this privilege path, including the risk from pull requests. The response is to protect the branch, gate risky triggers, and keep the build service account narrowly privileged. Default Cloud Build service account and trigger risks
Developer / trigger caller
|
v
Source repository --approved event--> Cloud Build
| runs as cloud-build-cicd
v
Artifact Registry
|
v
Cloud Run
| runs as cloud-run-runtime
v
Only the APIs the application needs
Four identities must not be confused:
| Identity | Purpose | Permissions in this guide |
|---|---|---|
| Caller or trigger creator | Creates or invokes builds and triggers | Control-plane permissions such as cloudbuild.builds.create; permission to act as the selected build service account |
| Build execution service account | Executes Docker and gcloud build steps | Write the selected repository, write logs, deploy Cloud Run, and attach only the runtime service account |
| Cloud Run runtime service account | Identity used by the running application | No project role by default; add only roles required by the application |
| Cloud Build service agent | Google-managed service identity used internally by Cloud Build | roles/cloudbuild.serviceAgent; do not use it as the build or runtime identity |
The Google-managed service agent has the form [email protected]. It is different from both a user-managed build account and the legacy [email protected] account. Cloud Build service agent documentation
Since the 2024 default-service-account change, projects can use either the Compute Engine default service account or the legacy Cloud Build service account, depending on project and organization history. Check rather than guess:
gcloud builds get-default-service-account --project="$PROJECT_ID"
gcloud builds get-default-service-account asks Cloud Build which identity it would select by default.--project="$PROJECT_ID" makes the target explicit instead of relying on local CLI state.Google recommends a user-managed service account because default accounts can have broader permissions than the pipeline needs. This guide therefore specifies cloud-build-cicd explicitly. Default service account change and gcloud builds get-default-service-account
export PROJECT_ID="your-project-id"
export REGION="us-central1"
export REPOSITORY="app-images"
export SERVICE="web"
export BUILD_SA_NAME="cloud-build-cicd"
export RUNTIME_SA_NAME="cloud-run-runtime"
export BUILD_SA="${BUILD_SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"
export RUNTIME_SA="${RUNTIME_SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"
Line by line:
PROJECT_ID selects the Google Cloud project that owns the build, repository, and service.REGION keeps Cloud Build, Artifact Registry, and Cloud Run in one region where supported.REPOSITORY names the dedicated Docker repository.SERVICE names the Cloud Run service.BUILD_SA_NAME names the identity that executes build steps.RUNTIME_SA_NAME names the separate identity used by the deployed container.BUILD_SA constructs the full build service-account email.RUNTIME_SA constructs the full runtime service-account email.These shell variables exist only in the current terminal. They are not credentials.
gcloud config set project "$PROJECT_ID"
gcloud services enable \
cloudbuild.googleapis.com \
artifactregistry.googleapis.com \
run.googleapis.com \
iam.googleapis.com
Line by line:
gcloud config set project changes the active CLI project. Commands below still pass resource names explicitly where practical.gcloud services enable enables every API listed on the following lines.cloudbuild.googleapis.com provides builds and triggers.artifactregistry.googleapis.com provides the private Docker repository.run.googleapis.com provides Cloud Run deployments.iam.googleapis.com provides user-managed service accounts.Enabling APIs requires serviceusage.services.enable, commonly granted through roles/serviceusage.serviceUsageAdmin. Do this as a bootstrap administrator, not as the build account. Cloud Build setup requirements
gcloud iam service-accounts create "$BUILD_SA_NAME" \
--display-name="Cloud Build CI/CD executor" \
--description="Builds images and deploys only the web service"
gcloud iam service-accounts create "$RUNTIME_SA_NAME" \
--display-name="Cloud Run web runtime" \
--description="Runtime identity for the web service"
For each command:
gcloud iam service-accounts create creates a user-managed identity; it does not create a downloadable key.--display-name gives administrators a readable name.--description records the account's single purpose.Do not run gcloud iam service-accounts keys create. Cloud Build and Cloud Run attach identities and issue short-lived credentials automatically. Google recommends avoiding user-managed keys because leaked private keys can be used as the service account without an additional sign-in challenge. Service-account key security
If automatic vulnerability scanning is available in your account, enable its API first:
gcloud services enable containerscanning.googleapis.com
gcloud artifacts repositories create "$REPOSITORY" \
--repository-format=docker \
--location="$REGION" \
--description="Deployment images for the web service" \
--immutable-tags \
--allow-vulnerability-scanning
Line by line:
containerscanning.googleapis.com enables Artifact Analysis container scanning.repositories create "$REPOSITORY" creates only the named repository.--repository-format=docker restricts it to Docker/OCI container images.--location="$REGION" places it in the selected region.--description documents its purpose; never put secrets in resource descriptions.--immutable-tags prevents an existing tag from being moved to another digest.--allow-vulnerability-scanning enables automatic scanning for this repository when the service and account support it.Immutable tags prevent silent tag replacement but require every build to use a new tag. Artifact Analysis scans new uploaded images and continues updating vulnerability metadata; it reports risk but does not, by itself, block deployment. Scanning is a paid feature in some configurations. Create an Artifact Registry repository and container scanning overview
gcloud artifacts repositories add-iam-policy-binding "$REPOSITORY" \
--location="$REGION" \
--member="serviceAccount:$BUILD_SA" \
--role="roles/artifactregistry.writer"
--location identifies the regional repository.--member selects the build identity.roles/artifactregistry.writer allows reading and writing artifacts but not repository administration.Artifact Registry supports repository-level grants, which reduce the impact of a compromised pipeline. Artifact Registry access control
gcloud projects add-iam-policy-binding "$PROJECT_ID" \
--member="serviceAccount:$BUILD_SA" \
--role="roles/logging.logWriter"
gcloud projects add-iam-policy-binding "$PROJECT_ID" \
--member="serviceAccount:$BUILD_SA" \
--role="roles/run.developer"
The first command grants only permission to write log entries. The second grants the Cloud Run create/update permissions needed for the first deployment. Each --member targets the build account, and each --role grants one predefined role.
roles/run.developer is project-scoped here because the first deployment must create the service. In a stricter production design, an administrator can create the service first, scope subsequent deploy permissions to that service where the resource hierarchy permits it, and remove the project-level grant. Do not replace these roles with Owner, Editor, Cloud Run Admin, Storage Admin, or Cloud Build Editor. Cloud Run deployment roles
gcloud iam service-accounts add-iam-policy-binding "$RUNTIME_SA" \
--member="serviceAccount:$BUILD_SA" \
--role="roles/iam.serviceAccountUser"
RUNTIME_SA, so the grant is not project-wide.roles/iam.serviceAccountUser supplies iam.serviceAccounts.actAs, which Cloud Run deployment needs to attach the runtime account.This grant does not give the build account all permissions held by the runtime account for ordinary API calls. It allows attaching that identity to the service, which is still security-sensitive; keep runtime permissions minimal. Cloud Run service identity
The runtime account receives no project role in this example. If the application later reads one Secret Manager secret or one database, grant the required role on that exact resource—not Editor on the project.
cloudbuild.yamlPlace this file beside the application's Dockerfile:
steps:
- id: build-image
name: gcr.io/cloud-builders/docker
args:
- build
- --tag
- ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/${_IMAGE}:$BUILD_ID
- .
- id: push-image
name: gcr.io/cloud-builders/docker
args:
- push
- ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/${_IMAGE}:$BUILD_ID
- id: deploy-private-service
name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
entrypoint: gcloud
args:
- run
- deploy
- ${_SERVICE}
- --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/${_IMAGE}:$BUILD_ID
- --region=${_REGION}
- --platform=managed
- --service-account=cloud-run-runtime@$PROJECT_ID.iam.gserviceaccount.com
- --quiet
substitutions:
_REGION: us-central1
_REPOSITORY: app-images
_IMAGE: web
_SERVICE: web
serviceAccount: projects/your-project-id/serviceAccounts/[email protected]
options:
logging: CLOUD_LOGGING_ONLY
| YAML | Meaning and security effect |
|---|---|
steps: | Starts the ordered list of containers Cloud Build will run. With no parallel waitFor, these steps run in order. |
id: build-image | Gives the first step a readable audit label. |
name: gcr.io/cloud-builders/docker | Runs Google's supported Docker builder. A builder is executable code with the build account's permissions, so it belongs in the trust boundary. |
args: | Starts the argument array passed directly to the builder; no shell interprets these values. |
build | Runs docker build. |
--tag | Assigns the full Artifact Registry image name. |
...:$BUILD_ID | Uses Cloud Build's unique build ID as an immutable tag. $BUILD_ID exists for manual and triggered builds. |
. | Uses the checked-out workspace as the Docker build context. Control it with a strict .dockerignore so credentials and irrelevant files are not copied. |
There is deliberately no --allow-unauthenticated. New Cloud Run services require authentication by default. An existing service keeps its existing IAM policy, so an administrator should inspect it with gcloud run services get-iam-policy "$SERVICE" --region="$REGION" and remove any unintended allUsers invoker binding outside this deployment pipeline. Manage roles/run.invoker separately for only the users, groups, or calling services that should invoke it. Also, repeatedly passing --no-allow-unauthenticated can require IAM-policy permissions that a least-privileged deployer should not have. Cloud Run deployment behavior
$COMMIT_SHA is available for supported trigger builds, but it can be empty for manually submitted builds. $BUILD_ID is therefore the safe universal tag. If you also want a commit tag, add it only in a trigger-specific pipeline and retain the build-ID or digest as the deployment identity. Cloud Build substitutions
Treat every custom substitution as untrusted input because an authorized caller can override it. This example passes substitutions as individual arguments rather than interpolating them into a shell command, and repository-scoped IAM prevents an overridden image path from writing to another repository. The initial project-level roles/run.developer grant is still broader: after an administrator creates the service, scope that role to the intended Cloud Run service where your resource policy supports it.
The example uses named Google builders for readability. For a high-assurance pipeline, review every builder and pin an approved builder image by digest; mutable builder tags can change what code runs with the build account's authority. Apply the same rule to Docker FROM images, use lockfiles, and use deterministic installers such as npm ci. Pinning improves reproducibility but requires an update process so security fixes are not missed. Safeguard builds and dependency management
Before running this command, replace both your-project-id values in the top-level serviceAccount field of cloudbuild.yaml. Do not replace that field with $PROJECT_ID; top-level service-account selection happens before build substitutions are evaluated.
gcloud builds submit \
--config=cloudbuild.yaml \
--project="$PROJECT_ID" \
.
Line by line:
gcloud builds submit uploads the source and creates a build.--config=cloudbuild.yaml chooses the reviewed pipeline file.--project makes the build project explicit.. selects the current directory as source.The human submitting this build needs cloudbuild.builds.create and iam.serviceAccounts.actAs on the selected build account. Those are caller permissions, not permissions the running application needs. Restrict them because creating a build allows code execution with the build identity. Cloud Build IAM permissions
First, give the trigger's selected service account only the permission Cloud Build requires to create a triggered build. A project custom role avoids granting the broader Cloud Build Editor role:
gcloud iam roles create cloudBuildTriggerRunner \
--project="$PROJECT_ID" \
--title="Cloud Build Trigger Runner" \
--description="Creates builds from an approved trigger" \
--permissions="cloudbuild.builds.create" \
--stage="GA"
gcloud projects add-iam-policy-binding "$PROJECT_ID" \
--member="serviceAccount:$BUILD_SA" \
--role="projects/$PROJECT_ID/roles/cloudBuildTriggerRunner"
gcloud iam service-accounts add-iam-policy-binding "$BUILD_SA" \
--member="serviceAccount:$BUILD_SA" \
--role="roles/iam.serviceAccountUser"
The first command creates a project-local role containing exactly cloudbuild.builds.create; the second grants it to the build account. The final command lets the trigger account act as itself, which Google documents as required when the same account triggers and runs a build. Because the policy is attached to BUILD_SA, it does not allow acting as any other service account. Some organizations centralize custom-role management. The predefined roles/cloudbuild.builds.builder is an official fallback but contains more permissions and should be reviewed before use. Cloud Build roles, default service account trigger requirements, and trigger permission troubleshooting
After connecting the GitHub repository to Cloud Build, create a main-branch trigger:
gcloud builds triggers create github \
--name="secure-main-deploy" \
--region="$REGION" \
--repo-owner="YOUR_GITHUB_ORG" \
--repo-name="YOUR_REPOSITORY" \
--branch-pattern='^main$' \
--build-config="cloudbuild.yaml" \
--service-account="projects/$PROJECT_ID/serviceAccounts/$BUILD_SA" \
--require-approval
Line by line:
triggers create github creates a trigger for an already connected GitHub repository.--name gives it a stable audit name.--region selects the trigger region.--repo-owner restricts the source owner or organization.--repo-name restricts the source repository.--branch-pattern='^main$' matches only the exact main branch, not similarly named branches.--build-config uses the reviewed file from the repository.--service-account explicitly selects the build identity.--require-approval leaves each triggered build pending until an authorized approver accepts it.For triggered builds, the service account configured on the trigger overrides and ignores serviceAccount in cloudbuild.yaml. Set both so manual and triggered builds are explicit. Protect main with required reviews and restrict who can edit triggers or act as the build account. For pull-request triggers, use comment control for trusted collaborators and manual approval for public or external contributions. Create and manage triggers and gate builds on approval
Give roles/cloudbuild.builds.approver to a small group that is independent from routine committers. Remember that a user with Cloud Build Editor can change whether approval is required, so trigger administration is a privileged role.
This pipeline needs no secret to push to Artifact Registry or deploy Cloud Run: attached service accounts provide short-lived credentials. Application secrets normally belong on the Cloud Run runtime configuration, not inside the image.
If a build step genuinely needs a third-party token, grant the build account roles/secretmanager.secretAccessor on that one secret, then expose it only to that step:
steps:
- id: command-that-needs-token
name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
entrypoint: bash
secretEnv:
- THIRD_PARTY_TOKEN
args:
- -ceu
- some-command --token="$$THIRD_PARTY_TOKEN"
availableSecrets:
secretManager:
- versionName: projects/$PROJECT_ID/secrets/third-party-token/versions/1
env: THIRD_PARTY_TOKEN
secretEnv limits injection to this step.-c tells Bash to run the following command, while -e and -u stop on errors and unset variables.$$THIRD_PARTY_TOKEN escapes Cloud Build substitution so the step receives the secret environment variable.availableSecrets maps one Secret Manager version to the local variable.1 is reproducible; latest simplifies rotation but can change without a source commit.Never echo secrets, enable shell tracing around them, pass them as ordinary substitutions, bake them into images, or print environment dumps. Build logs are durable data. Use Secret Manager secrets in Cloud Build
Cloud Build can generate verifiable provenance containing image digests, source locations, inputs, and build details. For container provenance, Google requires the images field and requestedVerifyOption: VERIFIED; an explicit docker push step does not generate provenance. That creates an important design tradeoff: this single-build example pushes before it deploys, so it is convenient but not the strongest supply-chain design. Generate and validate build provenance
For production, split the flow:
images: and requestedVerifyOption: VERIFIED.The build-only configuration ends like this:
images:
- ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/${_IMAGE}:$BUILD_ID
options:
logging: CLOUD_LOGGING_ONLY
requestedVerifyOption: VERIFIED
images asks Cloud Build to publish and record the result after steps complete. VERIFIED makes the build fail if attestations and provenance cannot be produced. The operational cost is a second, separately authorized deployment stage.
Automatic scanning finds known vulnerabilities; it does not decide whether risk is acceptable. Add a policy step or release gate that rejects severity above your threshold and has a documented exception process. Binary Authorization for Cloud Run can enforce deployment rules, such as requiring an image built by Cloud Build or signed by an approved attestor. Roll it out in audit/test mode before enforcement so a policy mistake does not block emergency releases. Protect Artifact Registry artifacts and secure Cloud Run deployments with Binary Authorization
Use a private pool when builds need controlled VPC access, fixed network paths, or restricted egress. VPC Service Controls can reduce data-exfiltration risk, but Cloud Build protection is available only for private-pool builds and requires repository, logging, DNS, firewall, and dependency-egress planning. Enforce constraints/cloudbuild.allowedWorkerPools so developers cannot bypass the approved pools. The tradeoffs are cost, setup complexity, and possible loss of public dependency access. Cloud Build private pools with VPC Service Controls
Cloud Build emits Cloud Audit Logs for administrative and access activity. Query build events with:
protoPayload.serviceName="cloudbuild.googleapis.com"
Route relevant logs to a retention-controlled log bucket or SIEM and alert on trigger changes, IAM changes, rejected approvals, unusual principals, and builds outside approved pools. Enable Data Access audit logs where required; access to those logs is itself sensitive. Logs cannot rescue a printed secret, so prevent secret output at the source. Cloud Build audit logging
gcloud builds get-default-service-account was checked, but the pipeline specifies a user-managed build account anyway.These commands permanently remove the example resources. Review every variable before running them:
gcloud builds triggers delete "secure-main-deploy" --region="$REGION"
gcloud run services delete "$SERVICE" --region="$REGION"
gcloud artifacts repositories delete "$REPOSITORY" --location="$REGION"
gcloud iam service-accounts delete "$BUILD_SA"
gcloud iam service-accounts delete "$RUNTIME_SA"
gcloud iam roles delete cloudBuildTriggerRunner --project="$PROJECT_ID"
Line by line, the commands delete the trigger, deployed service, image repository and all contained images, build account, runtime account, and custom trigger role. Deleting the repository removes stored artifacts, so retain any image and audit evidence required by your rollback or compliance policy first.
id: push-image | Names the publishing step. |
second Docker name | Uses the same Docker builder to publish the image. |
push | Uploads the tagged image. Repository-scoped Writer is sufficient. |
image URI after push | Pushes exactly the image created by the first step. |
id: deploy-private-service | Names the deployment step. |
Cloud SDK name | Supplies the gcloud executable. This builder also executes with build-account permissions. |
entrypoint: gcloud | Runs gcloud directly instead of a shell. |
run, deploy, ${_SERVICE} | Executes gcloud run deploy web. |
--image=...:$BUILD_ID | Deploys the build-specific image tag. Cloud Run resolves a tag to a digest, and that revision continues serving that digest. |
--region=${_REGION} | Deploys in the selected region. |
--platform=managed | Targets fully managed Cloud Run. |
--service-account=... | Makes the service run as the dedicated runtime account, not a default account. |
--quiet | Prevents an unattended pipeline from waiting for interactive confirmation. |
substitutions: | Defines approved configuration values that may be overridden by the build request or trigger. |
_REGION | Sets the default region. Custom substitutions must begin with an underscore. |
_REPOSITORY | Sets the target repository name. |
_IMAGE | Sets the image name inside that repository. |
_SERVICE | Sets the Cloud Run service name. |
serviceAccount: | Selects the user-managed account for manually submitted builds. It must use the full literal resource name; replace both your-project-id values before committing the file. Cloud Build does not expand substitutions in this top-level field. |
options: | Starts Cloud Build execution options. |
logging: CLOUD_LOGGING_ONLY | Stores logs in Cloud Logging, which is a supported requirement when using a user-managed build account. |