How to Use When Condition in Jenkins Pipeline
In Jenkins Pipeline, use the
when block inside a stage to run that stage only if a specified condition is true. The when block supports conditions like branch name, environment variables, or custom expressions to control pipeline flow.Syntax
The when block is placed inside a stage to define conditions for running that stage. It supports multiple condition types like branch, environment, expression, and more.
Basic structure:
stage('Stage Name') {
when {
conditionType 'value'
}
steps {
// steps to run if condition is true
}
}Explanation:
- stage('Stage Name'): Defines a pipeline stage.
- when: Starts the condition block.
- conditionType 'value': Condition to check (e.g., branch 'main').
- steps: Commands to run if condition passes.
groovy
stage('Example Stage') { when { branch 'main' } steps { echo 'This runs only on main branch' } }
Example
This example shows a Jenkins Declarative Pipeline with two stages. The second stage runs only if the branch is main.
groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Building...'
}
}
stage('Deploy') {
when {
branch 'main'
}
steps {
echo 'Deploying to production'
}
}
}
}Output
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] echo
Building...
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Deploy)
[Pipeline] echo
Deploying to production
[Pipeline] }
[Pipeline] // stage
Common Pitfalls
Common mistakes when using when conditions include:
- Using
whenoutside of astageblock, which is invalid. - Incorrect syntax like missing quotes or wrong condition names.
- Expecting
whento controlstepsdirectly instead of entire stages. - Not handling multiple conditions properly (use
allOforanyOffor combining).
Example of wrong and right usage:
groovy
stage('Wrong Usage') { steps { when { branch 'main' } echo 'This will fail' } } stage('Right Usage') { when { branch 'main' } steps { echo 'This runs only on main branch' } }
Quick Reference
Common when condition types:
| Condition Type | Description | Example |
|---|---|---|
| branch | Runs stage on specific branch | when { branch 'main' } |
| environment | Runs stage if env var matches | when { environment name: 'DEPLOY', value: 'true' } |
| expression | Runs stage if Groovy expression is true | when { expression { return params.RUN_STAGE } } |
| not | Negates a condition | when { not { branch 'develop' } } |
| allOf | All conditions must be true | when { allOf { branch 'main'; environment name: 'DEPLOY', value: 'true' } } |
| anyOf | Any condition is true | when { anyOf { branch 'main'; branch 'release' } } |
Key Takeaways
Use the when block inside a stage to control if it runs based on conditions.
Common conditions include branch, environment variables, and custom expressions.
The when block applies to entire stages, not individual steps.
Combine multiple conditions with allOf or anyOf for complex logic.
Always place when inside a stage block to avoid syntax errors.