How to Use when {} Conditions in a Jenkins Pipeline
The when {} directive runs a stage only when its condition matches: a branch, an env value, an expression, or a parameter.
Place when {} at the top of a stage. Conditions like branch, environment, expression, and allOf/anyOf decide whether the stage executes.
Conditional stage execution
The deploy stage runs only on the main branch and only when the deploy parameter is true.
Jenkinsfile
pipeline {
agent any
parameters {
booleanParam(name: 'DEPLOY', defaultValue: false)
}
stages {
stage('Deploy') {
when {
allOf {
branch 'main'
expression { return params.DEPLOY }
}
}
steps {
sh './deploy.sh'
}
}
}
}Gotchas
- Combine conditions with
allOf/anyOf;not {}inverts a condition. branchonly works on multibranch pipelines; for plain jobs useexpression { env.BRANCH_NAME == 'main' }.- A skipped stage shows as not-run in the UI, not as failed.
Key takeaways
when {}gates a stage on branch, env, expression, or params.- Combine conditions with
allOf,anyOf, andnot. branchneeds a multibranch pipeline to evaluate.
Related guides
How to Use Parameters in a Jenkins PipelineUse the parameters block in a Jenkins declarative pipeline to add a Build with Parameters form with string, c…
How to Run a Stage Only on a Branch Pattern in a Jenkins PipelineRun a Jenkins pipeline stage only on matching branches with when { branch } using glob or regex comparators,…