0
0
Jenkinsdevops~3 mins

Why Stage conditions with when directive in Jenkins? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple directive can save you hours of debugging and wasted builds!

The Scenario

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.

The Problem

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 Solution

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.

Before vs After
Before
stage('Build') {
  steps {
    script {
      if (env.BRANCH_NAME == 'main') {
        // build steps
      }
    }
  }
}
After
stage('Build') {
  when {
    branch 'main'
  }
  steps {
    // build steps
  }
}
What It Enables

You can create smarter pipelines that run exactly what you need, saving time and avoiding errors.

Real Life Example

For example, only run deployment stages when code is merged into the main branch, and skip them for feature branches automatically.

Key Takeaways

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.