Conditional Stages with when
The when directive runs a stage only if a condition is met, such as being on a specific branch.
Syntax
when { branch 'main' }The when directive makes a stage run conditionally. If the condition is false, Jenkins skips the whole stage.
Common conditions
branch 'main'— only on the main branch.environment name: 'DEPLOY', value: 'true'— match an env variable.expression { params.RELEASE == true }— any Groovy expression.changeRequest()— only for pull requests.
Combining conditions
Wrap several conditions in allOf, anyOf, or not for AND / OR / NOT logic.
Example
pipeline {
agent any
stages {
stage('Build') {
steps { sh 'make build' }
}
stage('Deploy to Production') {
when {
branch 'main'
}
steps {
echo 'Deploying to production (main branch only)'
}
}
stage('Deploy Preview') {
when {
changeRequest()
}
steps {
echo 'Deploying a PR preview environment'
}
}
}
}When to use it
- A deploy stage uses when { branch 'main' } to ensure code is only deployed to production from the main branch.
- A release-notes stage uses when { tag 'v*' } to run only on version tags, skipping it for every regular commit.
- A smoke-test stage uses when { environment name: 'RUN_SMOKE', value: 'true' } controlled by a build parameter.
More examples
Run stage only on main branch
Skips the Deploy stage on all branches except main, preventing accidental production deploys.
stage('Deploy') {
when { branch 'main' }
steps {
sh 'helm upgrade myapp ./chart --namespace production'
}
}Run stage on version tags
Runs the release publish step only when the pipeline is triggered by a semantic-version Git tag.
stage('Publish Release') {
when { tag pattern: 'v\\d+\\.\\d+\\.\\d+', comparator: 'REGEXP' }
steps {
sh 'mvn deploy -P release'
}
}Compound when condition
Combines a branch condition and an environment variable check with allOf so both must be true.
stage('Integration Tests') {
when {
allOf {
branch 'main'
environment name: 'RUN_INTEGRATION', value: 'true'
}
}
steps { sh './run-integration.sh' }
}
Discussion