How to Use Jenkins Multibranch Pipeline: Setup and Example
Use a
Multibranch Pipeline in Jenkins to automatically create pipelines for each branch in your source code repository. Configure it by selecting your repository and Jenkins will scan branches, creating jobs for each with their own Jenkinsfile. This helps automate CI/CD for multiple branches without manual setup.Syntax
The Multibranch Pipeline is configured in Jenkins UI, not by a single script. It scans your repository branches and runs the Jenkinsfile found in each branch root.
Key parts:
- Branch Source: The repository URL and credentials.
- Scan Repository Triggers: How often Jenkins checks for new branches or changes.
- Jenkinsfile: Pipeline script stored in each branch.
groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
echo "Building branch ${env.BRANCH_NAME}"
}
}
}
}Example
This example shows a simple Jenkinsfile for a Multibranch Pipeline that prints the branch name during build.
groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
echo "Building branch ${env.BRANCH_NAME}"
}
}
}
}Output
[Pipeline] echo
Building branch feature-xyz
[Pipeline] End of Pipeline
Common Pitfalls
- Not having a
Jenkinsfilein each branch causes Jenkins to skip that branch. - Incorrect repository credentials prevent branch scanning.
- Forgetting to set scan triggers means new branches won't build automatically.
- Using legacy pipeline jobs instead of Multibranch Pipeline loses automation benefits.
groovy
/* Wrong: No Jenkinsfile in branch */ // Jenkins will not build this branch /* Right: Add Jenkinsfile to branch root */ pipeline { agent any stages { stage('Build') { steps { echo "Building branch ${env.BRANCH_NAME}" } } } }
Quick Reference
- Multibranch Pipeline: Automatically creates jobs per branch.
- Jenkinsfile: Must be in each branch root.
- Branch Source: Connect your repo (GitHub, Bitbucket, etc.).
- Scan Triggers: Schedule scans to detect new branches.
- Environment Variable:
BRANCH_NAMEgives current branch name.
Key Takeaways
Multibranch Pipeline automates building all branches with their own Jenkinsfile.
Ensure each branch has a Jenkinsfile at the root for Jenkins to build it.
Configure repository and scan triggers in Jenkins to detect new branches automatically.
Use the BRANCH_NAME environment variable inside Jenkinsfile to customize builds per branch.
Avoid manual job creation for each branch by using Multibranch Pipeline.