As part of our CI/CD process, we need to keep our feature branches up-to-date with the master branch. This helps prevent merge conflicts and ensures our code is always based on the latest stable version. I recently built a Google Cloud Build pipeline to automate this tedious task.
This post will walk you through the key components of the Cloud Build YAML file that makes this happen.
## ⚙️ The Cloud Build Pipeline Explained
This pipeline consists of two main steps: configuring SSH access to GitHub and running the rebasing logic using gh
CLI.
- 🔐 SSH Key Configuration To interact with GitHub in a non-interactive way, the pipeline needs an SSH key. We store this securely in Google Secret Manager. The first step retrieves this key and configures SSH for the subsequent Git commands.
|
|
secretEnv
: This field is used to inject the secretGITHUB_SSH_KEY
from Secret Manager into the build step’s environment. The$
is escaped with$$
so that the value is not substituted during the build config parsing, but rather at runtime.volumed
: We use a named volume to ensure the configured SSH key persists between build steps. This allows the rebasing step to use the same SSH configuration.
- 🔄 Rebasing All Open Pull Request Branches
This is the core of the automation. This step fetches all open pull requests using the
gh
CLI and then iterates through each one to perform the rebase.
|
|
name
: We use a custom-build Docker image that includes thegh
CLI. This allows us to interact with the GitHub API to list open PRs._OPEN_PR_BRANCHES
: Thegh pr list
command is used to get a list of all open pull requests and extracts their head branch names using ajq
query.- Rebasing Loop: The
for
loop iterates through each of the open branches. For each one:- It checks for an incomplete rebase from a previous run and aborts it.
- It checks out the feature branch.
- It performs a
git rebase origin/master
. - It performs a
git push --force-with-lease
, which is a safer version of a force push.
This pipeline automates a key maintenance task, saving developers time and keeping our repository clean and organized.