How to get the current branch name in GitHub Actions can be useful for workflows that trigger off of multiple branches of a GitHub repository. The reason this can be useful is that the branch name may be important to mark or tag the code release in some way (i.e. tag a docker image), or maybe even vary the deployment of the code by environment. Regardless of the reason you need to get the name of the current Git repo branch, just rest assured that GitHub Actions does support retrieving it. This article explains the what is necessary to get the current Git repo branch name within a workflow.
Table of Contents
Methods of Getting the Current Git Branch Name
GitHub provides a variety of environment variables that contain useful information, extracting just the branch name from these variables requires a bit of manipulation. This article explores a couple different methods to retrieve the current repository branch name within a GitHub Actions workflow. These methods will help you streamline your CI/CD pipeline by ensuring you can accurately and efficiently use the branch name for tagging, configuration, and other automated tasks.
Using Shell Parameter Expansion
Shell parameter expansion provides a flexible way to handle strings and variables in shell scripts. By leveraging specific patterns and operators, you can modify the content of variables without the need for external tools or complex commands. This is particularly useful in CI/CD pipelines, where simplicity and performance are key.
In a GitHub Actions workflow, the GITHUB_REF variable holds the reference to the branch or tag that triggered the workflow. For branches, this reference is usually in the format refs/heads/<branch-name>. To use the branch name for tasks like tagging Docker images, we need to strip away the refs/heads/ prefix. Shell parameter expansion can be a simple solution to get this done.
name: Extract Branch Name
on:
push:
branches:
- '*'
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Get branch name
run: echo "Branch name is ${GITHUB_REF#refs/heads/}"
In the context of GitHub Actions, the shell parameter expansion feature can be particularly useful for extracting the branch name from the GITHUB_REF environment variable, which typically contains the full reference of the branch or tag that triggered the workflow.
Here’s a breakdown of the syntax and usage of this:
${variable#pattern}: This syntax is used to remove the shortest match ofpatterfrom the beginning of thevariable.GITHUB_REF: This is an environment variable available to GitHub Actions that contains the full reference to the repository branch or tag that triggered the workflow. For example, if the workflow was triggered by a push to a branch namedmain, the value ofGITHUB_REFwould berefs/heads/main.- The
#character: The#character in shell parameter expansion tells the shell to remove the shortest matching pattern from the beginning of the variable’s value. refs/heads/: This is the pattern we want to remove from the beginning of theGITHUB_REFvariables value.
Shell parameter expansion can be used to manipulate strings directly in the shell. By applying ${GITHUB_REF#refs/heads/}, you can easily shorten the branch name in your GitHub Actions workflows. This will enable you to use the branch name for tasks like tagging Docker images, setting environment configurations, or any other tasks where the branch name might be needed.
Storing the Branch Name
You may want to store the extracted branch name in an environment variable for use in subsequent steps. This can be done by appending the extracted branch name to the GITHUB_ENV file, which makes it available as an environment variable in later steps of the workflow:
- name: Extract branch name
id: extract_branch
run: echo "BRANCH_NAME=${GITHUB_REF#refs/heads/}" >> $GITHUB_ENV
Once the branch name is stored as an environment variable, then it can be access in a subsequent action as follows:
- name: Do Something with Branch Name
run: echo $BRANCH_NAME
By using shell parameter expansion, you can efficiently and cleanly extract the branch name from GITHUB_REF, simplifying your workflow and reducing the need for additional tools or complex commands. This method is both powerful and easy to implement, making it an excellent choice for handling branch names in your GitHub Actions workflows.
Using a Bash Command
When working with GitHub Actions, Bash commands can be used to parse and extract specific parts of environment variables, such as the branch name from GITHUB_REF. This allows you to dynamically tag Docker images, set environment-specific configurations, and more, all within your CI/CD pipeline.
- name: Get branch name
run: echo "Branch name is $(echo ${GITHUB_REF} | cut -d'/' -f3)"
Storing the Branch Name
You may want to store the extracted branch name in an environment variable for use in subsequent steps. This can be done by appending the extracted branch name to the GITHUB_ENV file, which makes it available as an environment variable in later steps of the workflow:
- name: Extract branch name
id: extract_branch
run: echo "BRANCH_NAME=$(echo ${GITHUB_REF} | cut -d'/' -f3)" >> $GITHUB_ENV
Once the branch name is stored as an environment variable, then it can be access in a subsequent action as follows:
- name: Do Something with Branch Name
run: echo $BRANCH_NAME
By using Bash commands like cut, you can precisely extract the branch name from GITHUB_REF in a manner that suits your workflow needs. This method provides a robust and flexible approach to handling branch names within GitHub Actions, allowing you to streamline your CI/CD processes and maintain a clean and efficient build pipeline.
Tagging Docker Image with the Branch Name
Once you have the branch name extracted, tagging your Docker images becomes straightforward. Using the branch name as part of your Docker image tags helps in several ways:
- Traceability: You can easily identify which branch a particular image was built from.
- Debugging: It helps in debugging issues by allowing you to recreate environments using images built from specific branches.
- Environment Segregation: Different branches (e.g.,
development,staging,production) can have their own Docker images, avoiding conflicts and ensuring environment-specific configurations.
Here’s a detailed example of a GitHub Actions workflow that builds and tags a Docker image with the current branch name:
name: CI/CD Pipeline
on:
push:
branches:
- '*'
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Log in to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Extract branch name
id: extract_branch
run: echo "BRANCH_NAME=$(echo ${GITHUB_REF#refs/heads/})" >> $GITHUB_ENV
- name: Build and push Docker image
run: |
docker build -t myapp:${{ env.BRANCH_NAME }} .
docker push myapp:${{ env.BRANCH_NAME }}
Extracting the Branch Name
- name: Extract branch name
id: extract_branch
run: echo "BRANCH_NAME=$(echo ${GITHUB_REF#refs/heads/})" >> $GITHUB_ENV
This step extracts the branch name from the GITHUB_REF variable and stores it in the environment variable BRANCH_NAME. The ${GITHUB_REF#refs/heads/} syntax removes the refs/heads/ prefix, leaving only the branch name. The extracted branch name is then appended to the GITHUB_ENV file, making it available for subsequent steps in the workflow.
Build and Push the Docker Image
- name: Build and push Docker image
run: |
docker build -t myapp:${{ env.BRANCH_NAME }} .
docker push myapp:${{ env.BRANCH_NAME }}
This step referenced the env.BRANCH_NAME that was previously set as follows:
docker build -t myapp:${{ env.BRANCH_NAME }} .: This command builds a Docker image from the current directory (denoted by.) and tags it with the branch name. The-toption specifies the tag for the image, which in this case ismyapp:<branch-name>.docker push myapp:${{ env.BRANCH_NAME }}: This command pushes the tagged image to DockerHub. By using the branch name as part of the tag, you ensure that each branch has its own distinct Docker image.
Understanding GITHUB_REF vs github.ref
In GitHub Actions workflows, two commonly used references within actions are github.ref and GITHUB_REF. In the previous examples we look at using GITHUB_REF. However, what about using github.ref?
github.ref is a property of the github context. It represents the full Git reference of the branch or tag that triggered the workflow. It can be accessed within expressions and is useful when you need to use the reference in various parts of your workflow.
jobs:
example-job:
runs-on: ubuntu-latest
steps:
- name: Print GitHub Ref
run: echo "The GitHub ref is: ${{ github.ref }}"
In this example, github.ref is used within an expression to print the Git reference.
When to use github.ref?
Understanding when to use github.ref and GITHUB_REF is usefule for effectively leveraging GitHub contexts in your workflows. Use github.ref for accessing Git references within expressions and conditional statements, and use GITHUB_REF for accessing Git references directly in shell commands and scripts. By utilizing these contexts appropriately, you can build more dynamic, flexible, and powerful GitHub Actions workflows.
It’s use to reference github.ref when:
- You need to access the Git reference within expressions.
- You want to use the Git reference in configuration or conditional statements in your workflow YAML file.
Here’s an example of referencing github.ref to configure conditional job execution within the GitHub Actions workflow based on the branch name:
jobs:
deploy:
if: ${{ github.ref == 'refs/heads/main' }}
runs-on: ubuntu-latest
steps:
- name: Deploy to Production
run: echo "Deploying to production..."
In this example, the deploy job runs only if the Git reference matches refs/heads/main.
Summary
By using GITHUB_REF or github.ref to access the GitHub repository branch name that triggered the workflow, you can add logic to your workflows that conditionally execute actions and/or tasks, such as: dynamically tag Docker images with the current branch name, or build and deploy code to target a specific environment. With the extracted branch name, you can build more flexible GitHub Actions workflows.
Original Article Source: GitHub Actions: Get Current Branch Name for Git Repo written by Chris Pietschmann (If you're reading this somewhere other than Build5Nines.com, it was republished without permission.)
Microsoft Azure Regions: Interactive Map of Global Datacenters
Create Azure Architecture Diagrams with Microsoft Visio
Book Launch: Ultimate Guide to Microsoft Certification
Azure CLI: List and Set Azure Subscription
Grove IoT Commercial Gateway Kit from Seeed





