How to Dynamically Use Branch Names in Jenkins Single-Branch Pipelines
Learn how to configure a Jenkins single‑branch pipeline to accept a branch name as a parameter, enabling dynamic code checkout by setting up a String parameter, using ${BranchName} in the pipeline script, and handling potential Lightweight checkout errors.
Introduction
In the previous article we showed how a single Docker command can quickly start Jenkins and explained the confusing environment variables. This article continues the discussion by showing how to use variables to dynamically select a branch in a Jenkins pipeline.
Jenkins Pipeline Types
Typical projects use Jenkins Pipeline for CI, which comes in two forms:
Pipeline (single‑branch)
Multibranch Pipeline (multiple branches)
When a Multibranch Pipeline is used, the branch name is resolved automatically, so the dynamic‑branch issue does not arise. The following guide shows how to achieve the same flexibility with a single‑branch pipeline.
Dynamically Using Branch Names in Jenkins
After creating a single‑branch pipeline, enable This project is parameterized, add a String parameter named BranchName with default value master. The UI looks like the following:
In the pipeline configuration, reference the parameter where the branch is specified, e.g.:
*/${BranchName}Note: Enabling Lightweight checkout may produce the following error:
stderr: fatal: Couldn't find remote ref refs/heads/${BranchName}Using this approach, the Jenkins pipeline pulls code based on the branch name at runtime. The same variable can also be used directly in a Jenkinsfile:
pipeline {
...
parameters {
string(name: 'BranchName', defaultValue: 'master', description: null)
}
stages {
stage('Test Branch Name') {
steps {
echo "${env.BranchName}"
}
}
}
}After clicking “Build with Parameters” on the left, you can input a branch name and run the job.
Conclusion
This technique of using parameters to dynamically reference variables is common in Jenkins and can be applied to other configuration fields, greatly increasing flexibility when maintaining Jenkins pipelines.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
