This chapter covers Cloud Build triggers and CI/CD pipelines, a core topic for the ACE exam under Domain 'Deploy Implement' (Objective 3.2). Cloud Build triggers are the mechanism that automatically starts builds in response to events like code pushes or schedule timers. Expect 2-4 exam questions on trigger types, configuration, and integration with source repositories. Mastery of this topic is essential for automating deployments in Google Cloud.
Jump to a section
Imagine a car manufacturing plant with a manual workshop and an automated assembly line. In the manual workshop (traditional CI/CD), a mechanic (developer) manually pushes a button to start each step: fetch parts (source code), weld the frame (compile), paint (run tests), install engine (package), and deliver to dealer (deploy). Each step requires human intervention and can be delayed if the mechanic is busy. Now consider the automated assembly line (Cloud Build with triggers). A sensor (trigger) detects when a new part shipment (code push) arrives at the loading dock (source repository). Automatically, a conveyor belt (build pipeline) moves the parts through pre-configured stations: a robotic arm (builder) fetches the exact part numbers (source code from Cloud Source Repositories, GitHub, or Bitbucket). At the welding station (compile step), the robot uses a specific welding pattern (build configuration in cloudbuild.yaml) and checks for defects (unit tests). The painting station (static analysis) applies a precise coat (code style checks) and dries it with heat (integration tests). Finally, the finished car (artifact) is loaded onto a truck (Container Registry) and delivered to the dealer (deployment to GKE, Cloud Run, or Compute Engine). The entire process is triggered automatically by the sensor, with no human waiting. If a station fails (build error), the line stops and an alert (Cloud Build notification) is sent to the floor manager (developer). The assembly line can also be triggered by a timer (scheduled trigger) to run nightly builds. This automation ensures consistent quality, fast turnaround, and no idle time between steps.
What Are Cloud Build Triggers?
Cloud Build triggers are event-driven mechanisms that automatically initiate a build process in Google Cloud Build. They eliminate manual intervention by starting a build when a specified event occurs in a connected source repository (Cloud Source Repositories, GitHub, or Bitbucket). Triggers are the foundation of CI/CD pipelines in GCP, enabling continuous integration and continuous delivery.
Why Use Triggers?
Without triggers, developers must manually start builds via gcloud builds submit or the Cloud Console. This is error-prone and slow. Triggers automate the build process, ensuring that every code change is built, tested, and deployed consistently. They enforce standards, reduce human error, and accelerate release cycles.
How Triggers Work Internally
A Cloud Build trigger is defined by:
- Source repository: The repo that contains the source code and build configuration.
- Event: What triggers the build (e.g., push to a branch, new tag, pull request).
- Build configuration: Either an inline build config or a cloudbuild.yaml file in the repo.
- Substitutions: Variables that customize the build per trigger.
- Service account: The identity used by Cloud Build to execute the build.
When an event occurs (e.g., a git push to a branch), the source repository sends a webhook to Cloud Build. Cloud Build validates the event against the trigger's criteria (e.g., branch regex). If it matches, Cloud Build creates a build resource and assigns a unique build ID. The build then runs according to the steps defined in the build configuration. Cloud Build pulls a builder image (e.g., gcr.io/cloud-builders/gcloud) for each step, executes the command, and stores artifacts (e.g., container images) in Container Registry or Artifact Registry. Build logs are streamed to Cloud Logging and can be viewed in the Cloud Console.
Trigger Types
Push trigger: Fires when a commit is pushed to a branch. You can specify a branch regex (e.g., ^main$, ^feature-.*).
Pull request trigger: Fires when a pull request is created or updated on a GitHub or Bitbucket repo. Not available for Cloud Source Repositories.
Tag trigger: Fires when a git tag is created (e.g., ^v[0-9]+\.[0-9]+\.[0-9]+$).
Scheduled trigger: Fires on a cron schedule (e.g., nightly builds). Uses Cloud Scheduler.
Manual invocation: You can also trigger builds manually via gcloud builds submit --trigger-name.
Build Configuration (cloudbuild.yaml)
The build configuration defines the steps Cloud Build executes. Example:
steps:
- name: 'gcr.io/cloud-builders/docker'
args: ['build', '-t', 'gcr.io/$PROJECT_ID/my-image', '.']
- name: 'gcr.io/cloud-builders/docker'
args: ['push', 'gcr.io/$PROJECT_ID/my-image']
- name: 'gcr.io/cloud-builders/gke-deploy'
args:
- 'run'
- '--filename=deployment.yaml'
- '--image=gcr.io/$PROJECT_ID/my-image'
- '--location=us-central1'
- '--cluster=my-cluster'Default values: timeout is 10 minutes per step, overall build timeout is 1 hour (configurable up to 24 hours). Each step runs in a separate container. Steps run sequentially unless you use waitFor: ['-'] to run in parallel.
Substitutions
Substitutions are variables you can use in the build config. Default substitutions include:
- $PROJECT_ID: GCP project ID.
- $BUILD_ID: Unique build ID.
- $REPO_NAME: Name of the source repo.
- $BRANCH_NAME: Branch name (for push triggers).
- $TAG_NAME: Tag name (for tag triggers).
- $SHORT_SHA: Short SHA of the commit.
You can also define custom substitutions in the trigger configuration. For example:
substitutions:
_DEPLOY_REGION: us-central1Then reference it as $_DEPLOY_REGION in the build config.
IAM Permissions
To create and manage triggers, you need:
- cloudbuild.triggers.create
- cloudbuild.triggers.get
- cloudbuild.triggers.list
- cloudbuild.triggers.update
- cloudbuild.triggers.delete
- cloudbuild.triggers.run
Predefined roles: Cloud Build Editor (roles/cloudbuild.builds.editor) includes trigger permissions. For builds, the service account used (default or custom) needs permissions to push images, deploy, etc.
Integration with Source Repositories
Cloud Source Repositories (CSR) require no additional webhook configuration. For GitHub or Bitbucket, you must connect the repository via Cloud Build's repository connection (using Cloud Build App for GitHub). Once connected, Cloud Build sets up webhooks automatically. For GitHub, you need to install the Google Cloud Build app and grant permissions. For Bitbucket, you use a workspace connection.
Build Triggers vs. Pub/Sub Notifications
Cloud Build can publish build status updates to Pub/Sub. You can set up a Pub/Sub trigger to start another build based on a successful build. This is useful for multi-step pipelines (e.g., build image -> trigger deployment build). However, this is different from source event triggers.
Verification Commands
List triggers:
gcloud builds triggers list --project=my-projectDescribe a trigger:
gcloud builds triggers describe my-trigger --region=us-central1Run a trigger manually:
gcloud builds triggers run my-trigger --branch=mainCreate a push trigger from command line:
gcloud builds triggers create push --name=my-push-trigger \
--repo=https://source.developers.google.com/p/my-project/r/my-repo \
--branch-pattern=^main$ \
--build-config=cloudbuild.yamlCreate a scheduled trigger:
gcloud builds triggers create scheduled --name=nightly-build \
--schedule="0 2 * * *" \
--timezone="America/New_York" \
--build-config=cloudbuild.yamlInteraction with Other GCP Services
Cloud Scheduler: Used by scheduled triggers. Cloud Scheduler sends a Pub/Sub message to Cloud Build.
Cloud Pub/Sub: Build status notifications can be sent to Pub/Sub topics.
Cloud Logging: Build logs are automatically sent to Cloud Logging.
Container Registry / Artifact Registry: Build artifacts are stored here.
GKE, Cloud Run, Compute Engine: Deploy targets.
Secret Manager: Store sensitive data (e.g., API keys) for use in builds.
Best Practices
Use branch-specific triggers: ^main$ for production, ^feature-.* for feature branches.
Use tag triggers for versioned releases.
Use substitutions to avoid hardcoding project-specific values.
Set appropriate timeouts to avoid runaway builds.
Use parallel steps for faster builds.
Store secrets in Secret Manager and access them via --secret env.
Use a dedicated service account with least privilege.
Common Pitfalls
Missing webhook: If triggers don't fire, check that the repository connection is healthy and webhooks are configured.
Incorrect branch regex: A branch named main will not match ^master$.
Build config not found: The cloudbuild.yaml must exist at the root of the repo unless you specify a different path.
Timeout: Builds that exceed the timeout are killed. Increase timeout if needed.
Permissions: The Cloud Build service account must have permissions to push images, deploy, etc.
Edge Cases
Pull request triggers from forked repos: By default, PRs from forked repos do not trigger builds for security reasons. You must enable it explicitly.
Scheduled triggers on shared VPC: Cloud Scheduler must be in the same project or have appropriate permissions.
Multiple triggers on same event: All matching triggers will fire, potentially causing duplicate builds. Use branch patterns to avoid overlap.
Summary of Key Numbers
Default build timeout: 10 minutes per step, 1 hour overall.
Maximum overall timeout: 24 hours.
Maximum number of steps: 100.
Maximum build config size: 1 MB.
Substitution variable format: $VARIABLE_NAME or _CUSTOM_VARIABLE (custom must start with underscore).
Cron expression: standard 5-field cron (min hour day month weekday).
Create a source repository connection
First, connect your source repository (Cloud Source Repositories, GitHub, or Bitbucket) to Cloud Build. For GitHub, install the Google Cloud Build app and authorize it to access your repos. For Bitbucket, create a workspace connection. For CSR, no extra steps are needed. This connection allows Cloud Build to listen for events via webhooks. The connection is managed under 'Repositories' in the Cloud Build console. You can also use the gcloud command: `gcloud builds connections create github --project=my-project --region=us-central1 --app-installation-id=...`.
Define the build configuration file
Create a `cloudbuild.yaml` file in the root of your repository. This file defines the build steps, substitutions, artifacts, and timeout. Each step specifies a builder image (e.g., `gcr.io/cloud-builders/docker`) and arguments. Steps run sequentially by default. Use `waitFor: ['-']` to run steps in parallel. The file must be valid YAML. Example: `steps: - name: 'gcr.io/cloud-builders/docker' args: ['build', '-t', 'gcr.io/$PROJECT_ID/my-image', '.']`. You can also use a Dockerfile or other build configs. The config file can be stored at a custom path (e.g., `config/cloudbuild.yaml`).
Create a trigger in Cloud Build
In the Cloud Console, navigate to Cloud Build > Triggers and click 'Create Trigger'. Fill in the trigger name, select the connected repository, and specify the event (push, pull request, tag, or schedule). For push triggers, provide a branch regex (e.g., `^main$`). For tag triggers, provide a tag regex (e.g., `^v[0-9]+\.[0-9]+\.[0-9]+$`). For scheduled triggers, set the cron schedule and timezone. Specify the build configuration (inline or from `cloudbuild.yaml`). Optionally, set substitutions and service account. Click 'Create'.
Push code to trigger the build
When you push a commit to the repository that matches the trigger's branch pattern, the source repository sends a webhook to Cloud Build. Cloud Build validates the event and starts a new build. The build is assigned a unique ID and appears in the Cloud Console under Build History. The build runs the steps in `cloudbuild.yaml`. You can monitor the build logs in real-time. If the build fails, Cloud Build sends a notification (if configured) and the build status is marked as 'FAILURE'.
Deploy the built artifact
After a successful build, the final step typically deploys the artifact. For example, a Docker image is pushed to Container Registry, then deployed to GKE using `gke-deploy` or to Cloud Run using `gcloud run deploy`. The deployment step uses the same Cloud Build service account. Ensure the service account has permissions to deploy. You can also use a separate trigger for deployment (e.g., triggered by a successful build via Pub/Sub). The deployed service is now live with the new code.
Enterprise Scenario 1: Multi-Environment Deployment Pipeline
A large e-commerce company uses Cloud Build triggers to automate deployments across dev, staging, and production environments. They have three branches: dev, staging, and main. Each branch has a push trigger that builds the code and deploys to the corresponding GKE cluster. The main branch trigger also runs integration tests and requires manual approval via Cloud Build approvals (Enterprise feature). They use substitutions for environment-specific variables (e.g., _CLUSTER_NAME). Common scale: 50+ developers pushing 200+ commits daily. Performance considerations: Build time averages 8 minutes; they use Kaniko cache for faster Docker builds. Misconfiguration: A developer accidentally pushed a breaking change to main that bypassed staging due to a misconfigured branch regex (allowed main and master both). They fixed it by tightening the regex to ^main$ and adding a staging gate.
Enterprise Scenario 2: Scheduled Nightly Builds for Compliance
A financial services firm must run nightly builds of their core banking application to ensure compliance with regulatory requirements. They use a scheduled trigger that runs at 2:00 AM EST every day. The build runs static code analysis, unit tests, and generates a compliance report. The report is stored in Cloud Storage and sent to auditors. They use Cloud Scheduler to trigger the build. Performance: The build takes 45 minutes; they increased the timeout to 2 hours. Misconfiguration: The cron expression was 0 2 * * * but the timezone was set to UTC, so builds ran at 2:00 AM UTC (9:00 PM EST). They corrected the timezone to America/New_York.
Enterprise Scenario 3: Pull Request Validation for Open Source Project
An open-source project hosted on GitHub uses Cloud Build triggers to validate pull requests. When a PR is created or updated, a trigger runs unit tests and linting. The trigger uses a pull request event and only runs on PRs from the main repo (not forks) for security. The build status is reported back to GitHub via the Cloud Build GitHub app. Common scale: 100+ PRs per week. Performance: Builds complete in under 5 minutes. Misconfiguration: A contributor from a forked repo expected their PR to trigger a build, but it didn't. They learned that PRs from forks are disabled by default. The project maintainer enabled 'Allow pull request builds from forked repositories' in the trigger settings.
What the ACE Exam Tests
The ACE exam focuses on Objective 3.2: 'Deploy Implement' – specifically, 'Implement CI/CD pipelines using Cloud Build'. You must know:
How to create and configure triggers (push, pull request, tag, scheduled).
The difference between inline and file-based build configs.
Substitution variables and their usage.
IAM permissions for triggers and builds.
How to connect GitHub and Bitbucket repositories.
How to view build logs and troubleshoot failures.
Common Wrong Answers
'Triggers can only be created in Cloud Console.' Wrong: You can also use gcloud builds triggers create and REST API.
'Scheduled triggers use Cloud Tasks.' Wrong: They use Cloud Scheduler.
'Cloud Build automatically deploys to Cloud Run without any configuration.' Wrong: You need explicit deployment steps in cloudbuild.yaml.
'Substitution variables must start with a dollar sign.' Wrong: They do, but custom substitutions must start with underscore (e.g., _MY_VAR).
Specific Numbers and Terms
Default build timeout: 10 minutes per step, 1 hour overall.
Maximum timeout: 24 hours.
Branch regex: ^main$ matches exactly main.
Tag regex: ^v[0-9]+\.[0-9]+\.[0-9]+$ for semantic versioning.
Cron: standard 5-field.
Build config file: cloudbuild.yaml by default.
Service account: [PROJECT-NUMBER]@cloudbuild.gserviceaccount.com.
Edge Cases
Pull request from fork: Disabled by default; must be enabled explicitly.
Multiple triggers on same branch: All matching triggers fire.
Build config in subdirectory: Use --build-config=path/to/cloudbuild.yaml.
Secret substitution: Use --substitutions with _SECRET and Secret Manager.
How to Eliminate Wrong Answers
If a question asks about automatic deployment, the answer must include a deployment step in the build config. Options that claim Cloud Build deploys automatically are wrong.
If a question involves scheduling, look for 'Cloud Scheduler' – not Cloud Tasks or Pub/Sub (though Pub/Sub is involved, the scheduler is the trigger source).
For permission questions, remember that the Cloud Build service account needs specific roles (e.g., roles/cloudbuild.builds.builder).
For trigger events, know that pull request triggers are only for GitHub/Bitbucket, not Cloud Source Repositories.
Cloud Build triggers automate build initiation based on source repository events (push, pull request, tag) or a schedule (via Cloud Scheduler).
Triggers can be created via Console, gcloud, REST API, or Terraform.
Branch regex patterns must be exact (e.g., `^main$` matches only 'main').
Custom substitution variables must start with an underscore (e.g., `_MY_VAR`).
Default build timeout is 10 minutes per step, 1 hour overall; max 24 hours.
Pull request triggers are only available for GitHub and Bitbucket, not Cloud Source Repositories.
Builds from forked repository pull requests are disabled by default for security.
The Cloud Build service account needs appropriate IAM roles to push images, deploy, etc.
Scheduled triggers use Cloud Scheduler, not Cloud Tasks.
Build logs are automatically sent to Cloud Logging and can be viewed in Console.
These come up on the exam all the time. Here's how to tell them apart.
Push Trigger
Fires on commits pushed to a branch.
Supports branch regex patterns (e.g., `^main$`).
Works with Cloud Source Repositories, GitHub, Bitbucket.
Ideal for CI on main branches and feature branches.
Can trigger deployment to staging/production.
Pull Request Trigger
Fires on creation or update of a pull request.
Only works with GitHub and Bitbucket (not Cloud Source Repositories).
Can be limited to PRs from the same repo (fork PRs disabled by default).
Ideal for validating changes before merging.
Build status is reported back to the PR (GitHub/Bitbucket).
Inline Build Config
Defined directly in the trigger creation form.
No need for a file in the repository.
Limited to simple builds (no custom steps beyond a few).
Harder to version control.
Good for quick tests or one-off builds.
File-Based Build Config (cloudbuild.yaml)
Stored in the repository as `cloudbuild.yaml`.
Can be versioned and reviewed via pull requests.
Supports complex multi-step builds, parallel steps, artifacts.
Can be reused across multiple triggers.
Best practice for production CI/CD.
Mistake
Cloud Build triggers can only be created via the Cloud Console.
Correct
Triggers can be created via `gcloud builds triggers create`, REST API, or Terraform, in addition to the Cloud Console.
Mistake
Scheduled triggers use Cloud Tasks to invoke builds.
Correct
Scheduled triggers use Cloud Scheduler, which sends a Pub/Sub message to Cloud Build. Cloud Tasks is not involved.
Mistake
Cloud Build automatically deploys artifacts to Cloud Run without any build configuration.
Correct
You must include a deployment step in `cloudbuild.yaml` (e.g., using `gcloud run deploy`). Cloud Build only executes the steps you define.
Mistake
Custom substitution variables can be named with any prefix.
Correct
Custom substitution variables must start with an underscore (`_`). Built-in substitutions start with `$` (e.g., `$PROJECT_ID`).
Mistake
Pull request triggers work with Cloud Source Repositories.
Correct
Pull request triggers are only supported for GitHub and Bitbucket repositories. Cloud Source Repositories do not have PR events.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
Create a push trigger with branch pattern `^main$`. In the Cloud Console, go to Cloud Build > Triggers, click 'Create Trigger', select your repository, choose 'Push' event, and enter `^main$` as the branch regex. Point to your `cloudbuild.yaml` file. Alternatively, use gcloud: `gcloud builds triggers create push --name=main-trigger --repo=... --branch-pattern=^main$ --build-config=cloudbuild.yaml`.
Yes. You need to connect your GitHub account to Cloud Build using the Google Cloud Build app. Install the app on your GitHub organization or account, and grant access to the private repository. Then you can create triggers for that repository. The app sets up webhooks automatically.
A push trigger fires when commits are pushed to a branch (e.g., `main`). A tag trigger fires when a git tag is created (e.g., `v1.0.0`). Use push triggers for continuous integration on branches, and tag triggers for release builds. Tag triggers often deploy to production after validating the tag.
Use substitution variables. Built-in substitutions like `$PROJECT_ID` are available. Custom substitutions must start with an underscore (e.g., `_MY_VAR`) and are defined in the trigger configuration. You can also use `env` in the build step to set environment variables directly: `- name: 'gcr.io/cloud-builders/docker' env: ['MY_VAR=value']`.
Possible reasons: (1) The repository connection is not set up correctly (check webhook health in GitHub/Bitbucket). (2) The branch pattern does not match the pushed branch (e.g., pattern `^main$` but branch is `master`). (3) The build config file path is incorrect. (4) The trigger is paused or disabled. Verify in Cloud Console under Triggers.
Yes, by using Pub/Sub notifications. Configure the first build to publish a message to a Pub/Sub topic on success. Then create a second trigger that listens to that Pub/Sub topic. This is useful for chaining builds (e.g., build image -> deploy).
You need the `cloudbuild.triggers.create` permission. This is included in the `Cloud Build Editor` role (`roles/cloudbuild.builds.editor`). For the build itself, the Cloud Build service account needs permissions to perform actions like pushing images (e.g., `storage.objectAdmin` for Container Registry).
You've just covered Cloud Build Triggers and CI/CD — now see how well it sticks with free ACE practice questions. Full explanations included, no account needed.
Done with this chapter?