How to Deploy Only From the Main Branch in Jenkins
A when { branch "main" } guard skips the deploy stage on every branch except main.
Keep build and test stages unconditional, then add when { branch "main" } to the deploy stage so feature branches build but never deploy.
Steps
- Leave build and test stages without a
whenso all branches run them. - Add
when { branch "main" }to the deploy stage. - On other branches the deploy stage is skipped, not failed.
Pipeline
Jenkinsfile
pipeline {
agent any
stages {
stage('Test') { steps { sh 'make test' } }
stage('Deploy') {
when { branch 'main' }
steps { sh './deploy.sh' }
}
}
}Gotchas
- The
branchcondition matches the SCM branch, available in Multibranch and most SCM-backed jobs. - For a freestyle single-branch job use
when { expression { env.GIT_BRANCH == 'origin/main' } }.
Related guides
How to Deploy on a Git Tag in JenkinsTrigger a Jenkins deploy stage only for Git tag builds with when { buildingTag } or a tag pattern, so release…
How to Deploy to Multiple Environments With Parameters in JenkinsLet an operator pick the target environment for a Jenkins deploy with a choice parameter, then map that choic…