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 a couple of 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

Now you can specify the branch name as a parameter when you next run your Job.

See my example repo on GitHub

A troubleshooting tip

If you see this error:

stderr: fatal: Couldn't find remote ref refs/heads/${BRANCH}

Then unchecking/unticking the Lightweight checkout box worked for me:

Observing the lightweight checkout option

Leave a Comment

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