How to Get the Short SHA for the GitHub Workflow?

How to Get the Short SHA for the GitHub Workflow

GitHub Actions has become an indispensable tool for automating CI/CD workflows and many other tasks. During the execution of these workflows, you might need to get the short SHA of the commit that triggered the workflow. This blog post guides you on how to achieve that.

GitHub Actions and Git SHA

GitHub Actions allows you to automate, customize, and execute software development workflows within your GitHub repositories. These workflows are defined in YAML files and can respond to various GitHub events such as push, pull requests, etc.

In Git, every commit is assigned a unique identifier called SHA (Secure Hash Algorithm). This is a 40-character hexadecimal string. However, it’s often more convenient to use the short SHA, which consists of the first 7 characters of the full SHA.

Now, let’s look into how to get this short SHA in a GitHub Actions workflow.

Getting the Short SHA in a GitHub Actions Workflow

To retrieve the short SHA of a commit in GitHub Actions, we can utilize the predefined github context. It offers various properties including github.sha which provides the full SHA string of the commit that triggered the workflow. We can then manipulate this string to get the short SHA.

Step by Step Guide

Here’s a step-by-step guide on how to get the short SHA:

  1. Create a GitHub Actions workflow file: In your repository, create a new file under the .github/workflows directory. Name it something like get_short_sha.yml. name: Get Short SHA on: [push] jobs: build: runs-on: ubuntu-latest steps: - name: 'Get Short SHA' run: echo "Short SHA is ${GITHUB_SHA::7}" This workflow is triggered on every push event. It contains a single job named build, which runs on the latest version of Ubuntu. Within this job, there’s a step that runs a command to print the short SHA. It uses the GITHUB_SHA environment variable, which holds the full SHA, and then trims it to the first 7 characters to get the short SHA.
  2. Push your workflow file to the GitHub repository: Commit your changes and push them to your repository. This will make the workflow available.
  3. Check the workflow run: Go to the ‘Actions’ tab in your GitHub repository to check the status of your workflows. When you push a commit, you should see the Get Short SHA workflow listed with its status. You can click on it to see the short SHA of the commit that triggered the workflow.

Conclusion

Retrieving the short SHA of a commit in a GitHub Actions workflow can be essential for various tasks like generating unique build IDs, tagging Docker images, etc. This guide showed you how to use the github.sha context and a bit of string manipulation to accomplish this.

Remember, GitHub Actions provides an extensive array of possibilities for automating workflows. The more you understand its features, the more powerful your workflows will become.