0
0
Jenkinsdevops~5 mins

Branch selection and branch specifier in Jenkins - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you want Jenkins to build code from a specific branch in your source control, you use branch selection and branch specifiers. This tells Jenkins exactly which branch to use for building and testing your project.
When you want to build the main branch to deploy the latest stable code.
When you want to test a feature branch before merging it into the main branch.
When you want to build a release branch for preparing a new version.
When you want Jenkins to automatically build pull requests from contributors.
When you want to run different jobs for different branches in the same repository.
Commands
This command updates the Jenkins job configuration with the specified YAML file that includes branch specifier settings.
Terminal
jenkins-jobs --conf jenkins.ini update my-job.yaml
Expected OutputExpected
Job my-job updated successfully
--conf - Specifies the Jenkins configuration file to use
Clones the repository locally to check available branches and verify branch names.
Terminal
git clone https://github.com/example/my-app.git
Expected OutputExpected
Cloning into 'my-app'... remote: Enumerating objects: 10, done. remote: Counting objects: 100% (10/10), done. remote: Compressing objects: 100% (8/8), done. remote: Total 10 (delta 1), reused 10 (delta 1), pack-reused 0 Receiving objects: 100% (10/10), done.
Lists all local and remote branches to find the exact branch name to specify in Jenkins.
Terminal
git branch -a
Expected OutputExpected
main feature/login remotes/origin/HEAD -> origin/main remotes/origin/main remotes/origin/feature/login
Triggers a Jenkins job build specifying the branch 'feature/login' to build that branch's code.
Terminal
jenkins-cli build my-job -p BRANCH=feature/login
Expected OutputExpected
Started build #15 for job my-job with parameter BRANCH=feature/login
-p - Passes parameters to the Jenkins job
Key Concept

If you remember nothing else from this pattern, remember: the branch specifier tells Jenkins exactly which branch to build from your source code repository.

Common Mistakes
Using an incorrect or misspelled branch name in the branch specifier.
Jenkins will fail to find the branch and the build will not start or will error out.
Always verify branch names with 'git branch -a' or your source control UI before specifying them in Jenkins.
Not updating the Jenkins job configuration after changing branch specifiers.
Jenkins will continue building the old branch and ignore your changes.
Update the Jenkins job configuration and reload or restart the job to apply new branch specifiers.
Summary
Use branch specifiers in Jenkins to tell it which branch to build from your repository.
Verify branch names with git commands before specifying them in Jenkins.
Trigger builds with parameters to select branches dynamically.