Discover how a simple directive can save you hours of debugging and wasted builds!
Why Stage conditions with when directive in Jenkins? - Purpose & Use Cases
Imagine you have a Jenkins pipeline with many stages, and you want some stages to run only under certain conditions, like only on a specific branch or when a file changes.
Without stage conditions, you have to write complex scripts inside each stage to check these conditions manually.
Manually checking conditions inside stages makes your pipeline scripts long and confusing.
It's easy to make mistakes, like running stages when you don't want to or skipping important ones.
This slows down your builds and wastes resources.
The when directive lets you declare conditions clearly and simply right at the stage level.
Jenkins then automatically decides whether to run the stage or skip it, keeping your pipeline clean and efficient.
stage('Build') { steps { script { if (env.BRANCH_NAME == 'main') { // build steps } } } }
stage('Build') { when { branch 'main' } steps { // build steps } }
You can create smarter pipelines that run exactly what you need, saving time and avoiding errors.
For example, only run deployment stages when code is merged into the main branch, and skip them for feature branches automatically.
Manual condition checks clutter pipeline scripts and cause errors.
The when directive simplifies conditional stage execution.
This leads to cleaner, faster, and more reliable pipelines.