Tagging Jenkins Builds with Git Commit Hashes & Messages

Kevin Guo
Level Up Coding
Published in
3 min readApr 22, 2021

--

Git -> Jenkins -> Docker

In this post, I’m writing about a small addition to a Jenkinsfile that retrieves commit hashes and messages so you can use it to tag your builds. In my case, I’m tagging releases on Octopus Deploy for a nice little quality of life upgrade.

To provide a bit of background, my team uses the setup depicted above for our CI/CD pipeline, consisting of Git, Jenkins, and Octopus Deploy. Git serves as our source code management tool. Jenkins plays a middleman role where whenever a new commit is pushed to the repository, it builds a Docker image for the repository using a Dockerfile inside of it, uploads the image to a registry, and then creates a corresponding release for it in Octopus Deploy. Octopus Deploy is used for release management and makes it convenient to deploy different versions of our code to different environments such as dev, staging, and production.

Octopus Releases

This setup serves fine for our needs, but one gripe with the way we implemented it was that our Octopus releases were only tagged with a version number, which made it difficult to tell which commits in the repository they corresponded to. For example, if I was trying to rollback production code to a specific commit, then I’d have to figure out the corresponding v.0.0.XX release by trying to match timestamps on the commit to timestamps on when the release was created, which are also off by a minute or so because it has to go through the CI/CD pipeline. Another coworker expressed some annoyance about this in passing, and it took less than an hour to fix this by adding commit hashes and messages to our Octopus releases.

Releases are now tagged with the corresponding commit, so no more guessing!

Luckily, Octopus has an option for specifying release notes when creating a release through its CLI. We do this in our Jenkinsfile, so now we just need to fetch the commit hash and message. It turns out that with the Git plugin for Jenkins that we already installed and use to fetch new code from the repository, we can fetch the commit hash as an environment variable:

RELEASE_NOTES = "$GIT_COMMIT"

To grab extra details such as the message, author, timestamp, etc. we can do:

RELEASE_NOTES = sh (script: """git log — format="medium" -1 ${GIT_COMMIT}""", returnStdout:true)

which runs git log with the commit hash as a shell script and returns it as a string using Jenkins’ returnStdout option.

So the only changes needed were an additional variable declaration and appending it as a release note to the end of the octo create-release command.

Before
After

--

--