How to evaluate Git branch name in a Jenkins pipeline using GitSCM?

226px-Jenkins_logo.svg.png

While working with Jenkins pipeline, you often want to clone a git repository and maybe even configure automatic build triggering upon commits or pull requests made on your repository.

A common flow style is cloning a git repository, checking out to your feature branch, merging master into it, running the build to see if master plays nice with your new code and if the build process finishes successfully - checking out master, merging your branch to master and pushing it to the repository.

If your repository is hosted in a known service such as GitHUB, GitLab, BitBucket, etc... then there's possibly a Jenkins plugin which knows how to work with each one of the services and supplies you with environment variables such as GITBRANCH, GITCOMMIT, BUILD_TAG, etc... so it is usually best practice to use such a plugin.

But if your git repository is hosted on Microsoft TFS for example then there's no such plugin (at the moment) which works well with the Pipeline type of Jenkins jobs.

In this case, you will probably use the "Pipeline: SCM Step" to clone the repository.

Example:

checkout([$class: 'GitSCM', branches: [[name: '/feature/']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '04f62bdf-e233-XXXX-XXXX-4fd5df294637', url: 'ssh://geek-kb@geek-kb.visualstudio.com:22/_git/scripts']]])

If you are not familiar by now with the Pipeline Syntax Generator, I suggest you check it out, it's really helpful and it can be found in any pipeline job page, on the left menu.

pipeline syntax

One of Jenkins environment variable is called BRANCH_NAME and while using a freestyle job, this variable evaluates to git branch name properly.

Problem:

In a pipeline job this variable is not evaluated properly and when you print it, the returned value is 'null'.

In order to implement the git flow I've mentioned earlier I have to know the name of the branch so I can checkout into it.

You can see in the following example how GitSCM checks out to a revision's SHA instead of the branch name itself:

branch name not evaluated

Solution:

Add [$class: 'LocalBranch', localBranch: "**"] to "extentions" in your checkout step.

Your checkout step should look like so:

checkout([$class: 'GitSCM', branches: [[name: '/feature/']], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'LocalBranch', localBranch: "**"]], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '04f62bdf-e233-XXXX-XXXX-4fd5df294637', url: 'ssh://geek-kb@geek-kb.visualstudio.com:22/_git/scripts']]])

You should now see how GitSCM checks out to the branch name properly, let's see how it works:

branch name evaluates

Now you can set BRANCH_NAME variable and use it in your pipeline.

Written by: Itai Ganot, 2017

itaig@tikalk.com