When Conditions for Conditional Execution
What you'll learn: How to control which stages run in your Jenkins pipeline based on dynamic runtime conditions.
The Core Idea
The when directive in Jenkins pipelines acts like a gatekeeper for your stages. Instead of running every stage every time, you can specify conditions that must be met before a stage executes. Think of it like a bouncer at a club checking IDs—only those who meet the criteria get in.
Jenkins provides several built-in condition types to match different scenarios:
Branch Conditions
Control execution based on which Git branch triggered the build:
when {
branch 'main'
}
This stage only runs when building the main branch. Perfect for deployment stages that should only run from production branches.
Environment Conditions
Check environment variable values:
when {
environment name: 'DEPLOY_ENV', value: 'production'
}
Runs only when the DEPLOY_ENV variable equals "production".
Changelog Conditions
Trigger stages based on commit messages:
when {
changelog '.*\\[deploy\\].*'
}
Executes only if recent commits contain "[deploy]" in their messages—useful for selective deployments.
Expression Conditions
Use Groovy expressions for complex logic:
when {
expression {
return env.BUILD_NUMBER.toInteger() > 10
}
}
This evaluates any boolean expression, giving you maximum flexibility.
Combining Conditions
You can use allOf, anyOf, and not to create sophisticated logic combining multiple conditions.
Key Takeaway: The when directive gives you fine-grained control over pipeline execution using branch, environment, changelog, and expression-based conditions—letting you build smarter, more efficient pipelines that only run stages when truly needed.