0
0
GcpHow-ToBeginner · 4 min read

How to Create a Build Trigger in Google Cloud Build

To create a build trigger in Cloud Build, use the Google Cloud Console or gcloud CLI to link your source repository and define when builds start automatically. The trigger watches for changes like commits or pull requests and starts builds based on your configuration.
📐

Syntax

The basic syntax to create a build trigger using the gcloud CLI is:

  • gcloud beta builds triggers create [TRIGGER_TYPE] --name=[TRIGGER_NAME] --repo=[REPO_NAME] --branch-pattern=[BRANCH_PATTERN] --build-config=[BUILD_CONFIG]
  • [TRIGGER_TYPE] can be github, bitbucket, or cloud-source-repositories.
  • [TRIGGER_NAME] is your chosen name for the trigger.
  • [REPO_NAME] is the source repository linked to Cloud Build.
  • [BRANCH_PATTERN] defines which branches start builds, e.g., ^main$.
  • [BUILD_CONFIG] is the path to your build configuration file, like cloudbuild.yaml.
bash
gcloud beta builds triggers create github \
  --name="my-trigger" \
  --repo="my-repo" \
  --branch-pattern="^main$" \
  --build-config="cloudbuild.yaml"
💻

Example

This example creates a build trigger that starts a build whenever code is pushed to the main branch of a GitHub repository named example-repo. It uses a cloudbuild.yaml file in the root of the repo to define build steps.

bash
gcloud beta builds triggers create github \
  --name="example-trigger" \
  --repo="example-repo" \
  --branch-pattern="^main$" \
  --build-config="cloudbuild.yaml"
Output
Created trigger [example-trigger].
⚠️

Common Pitfalls

  • Not linking the repository: The trigger must be connected to a source repository in Cloud Build.
  • Incorrect branch pattern: Use proper regex syntax; otherwise, triggers won't fire.
  • Missing or wrong build config path: The cloudbuild.yaml file must exist at the specified path.
  • Permissions: Ensure Cloud Build has access to the repository.
bash
Wrong:
gcloud beta builds triggers create github \
  --name="bad-trigger" \
  --repo="example-repo" \
  --branch-pattern="main" \
  --build-config="wrong-path.yaml"

Right:
gcloud beta builds triggers create github \
  --name="good-trigger" \
  --repo="example-repo" \
  --branch-pattern="^main$" \
  --build-config="cloudbuild.yaml"
📊

Quick Reference

ParameterDescription
--nameName of the build trigger
--repoSource repository linked to Cloud Build
--branch-patternRegex pattern for branches that trigger builds
--build-configPath to the build configuration file
--trigger-typeType of repository (github, bitbucket, cloud-source-repositories)

Key Takeaways

Create build triggers to automate builds on source code changes.
Use correct repository linking and branch regex patterns.
Specify the correct path to your build configuration file.
Ensure Cloud Build has permission to access your source repository.
Use the gcloud CLI or Cloud Console to create triggers easily.