New in Cloud Build: Substitution Variables for GitHub Pull Requests

Dave Stanke
2 min readJan 8, 2020

TL;DR: When a Cloud Build invocation is triggered by a GitHub Pull Request, you can now use the substitution values _HEAD_BRANCH, _BASE_BRANCH, _HEAD_REPO_URL, and _PR_NUMBER in the build config.

Google’s Cloud Build is a cloud-native CI/CD service available in Google Cloud Platform. When you connect it to GitHub repo hosting, you have a cloud-hosted development platform that someone else manages for you, and which is inexpensive (often, free). As part of a build configuration, Cloud Build provides a number of useful substitutions: these are variables like the ID of the GCP project you’re running in, or the commit SHA of the source code you’re building.

To kick off a build, Cloud Build can be configured to trigger from GitHub pull requests (PRs): when a new PR is created on GitHub, Cloud Build automatically starts a build of its source. Within that build, you might be interested in knowing info about the PR which caused it to happen. For example, you could stamp build information onto an artifact you generated, so reviewers can trace an application version back to the source from which it was built. Or you might want the build to interact with GitHub: perhaps you want to post some information as a PR comment for reviewers to see. These use cases require the build process to have access to the ID of the pull request. Unfortunately, that’s not something Cloud Build provides. Until now.

Let’s take the case of posting a comment onto a PR. I used to do a funky workaround using the GitHub API to answer the question: “Okay I have a commit here. What pull request does that commit belong to?”

The old way

Used to be, I had to scrape the API to figure out what Pull Request triggered a Cloud Build run.

Now that _PR_NUMBER is a built-in substitution, it’s much easier:

The new way

Making use of the _PR_NUMBER built-in substitution, I can delete all that jank.

Pretty Rad!

PS: Wondering what all that “entrypoint: bash” and “-c” stuff is about? Check out Mastering Google Cloud Build Syntax

--

--

Dave Stanke

DevOps Advocate at Google. My home is in Jersey City. My office is in New York. My opinions are all over the map, and may not reflect those of my employer.