Problem Statement
What does the 'when' directive do in Declarative Pipeline?
Explanation
The when directive controls conditional stage execution, running stages only when conditions are met. This enables branch-specific logic, environment-specific deployments, or skipping stages based on parameters. Conditions include branch (check branch name), environment (check environment variable), expression (evaluate Groovy expression), and more.
Common when conditions: branch 'main' (only on main branch), environment name: 'DEPLOY_ENV', value: 'prod' (only when variable set), expression { return params.DEPLOY } (based on parameter), not { branch 'develop' } (inverse condition). Example:
```groovy
stage('Deploy to Production') {
when {
branch 'main'
environment name: 'DEPLOY_PROD', value: 'true'
}
steps {
sh './deploy-prod.sh'
}
}
```
Additional conditions: allOf (all conditions must be true), anyOf (at least one condition true), changelog (commit message matches pattern), changeset (modified files match pattern), tag (TAG_NAME matches pattern), triggeredBy (specific trigger type). The beforeAgent option evaluates conditions before allocating agent, saving resources.
Understanding when directives enables flexible, intelligent pipelines that adapt behavior based on context, crucial for managing different branches, environments, and deployment scenarios.
