Using a dynamic Git branch name in a Jenkins job

Updated:

If you want to be able to dynamically give a Git branch to use in a Jenkins build then you’ll need to do three things.

Firstly, create a String parameter in your Job. This will be used to store your branch name:

String parameter in Jenkins

Then, in your Pipeline configuration, under Branches to build, add your parameter name inside the Branch Specifier box, surrounded by ${}. Jenkins will expand your variable when the job runs.

For example here, I’m telling Jenkins to find any Git ref spec that matches */${branchName}:

SCM config in Jenkins for Git with a dynamic branch name

Finally - and most importantly (this is the thing that took me ages to find out!) - you need to uncheck/untick the Lightweight checkout box.

If you don’t untick Lightweight checkout, you’ll get horrible errors like stderr: fatal: Couldn't find remote ref refs/heads/${BRANCH}. :(

Now you can specify the branch name as an argument when you run your Job.

Leave a Comment

You can use Markdown in your comment. To write code, indent lines by 4 spaces.