0
0
Jenkinsdevops~15 mins

Stage conditions with when directive in Jenkins - Deep Dive

Choose your learning style9 modes available
Overview - Stage conditions with when directive
What is it?
In Jenkins pipelines, the 'when' directive controls whether a stage runs or not based on specific conditions. It lets you decide if a stage should execute depending on things like branch name, environment variables, or build status. This helps make pipelines smarter and more efficient by skipping unnecessary steps. Without it, every stage would run every time, wasting time and resources.
Why it matters
The 'when' directive exists to save time and resources by running only the necessary parts of a pipeline. Without it, pipelines would always run all stages, even when some are irrelevant, causing longer build times and wasted compute power. This can slow down development and increase costs, especially in large projects with many stages.
Where it fits
Before learning 'when' conditions, you should understand basic Jenkins pipeline syntax and stages. After mastering 'when', you can explore advanced pipeline features like parallel stages, scripted pipelines, and shared libraries to build more complex automation.
Mental Model
Core Idea
The 'when' directive acts like a smart gatekeeper that decides if a pipeline stage should run based on set rules.
Think of it like...
Imagine a traffic light at an intersection that only lets cars go when the light is green. The 'when' directive is like that traffic light, allowing a stage to proceed only when conditions are right.
Pipeline
  ├─ Stage 1 (always runs)
  ├─ Stage 2
  │    └─ when: condition? ──> run or skip
  └─ Stage 3 (runs if previous conditions met)
Build-Up - 6 Steps
1
FoundationUnderstanding Jenkins Pipeline Stages
🤔
Concept: Learn what a stage is in Jenkins pipelines and how it structures the build process.
A Jenkins pipeline is made of stages. Each stage groups steps that perform a part of the build, like compiling code or running tests. Stages run in order unless told otherwise.
Result
You can organize your pipeline into clear steps that run sequentially.
Knowing stages lets you break down complex builds into manageable parts.
2
FoundationBasic Syntax of the when Directive
🤔
Concept: Introduce the 'when' directive syntax to conditionally run stages.
The 'when' directive goes inside a stage and uses conditions like 'branch', 'environment', or 'expression'. Example: stage('Test') { when { branch 'main' } steps { echo 'Running tests on main branch' } }
Result
The stage runs only if the branch is 'main'.
You can control stage execution based on simple conditions.
3
IntermediateUsing Multiple Conditions with when
🤔Before reading on: do you think multiple 'when' conditions run if any one is true, or only if all are true? Commit to your answer.
Concept: Learn how to combine multiple conditions using 'allOf' and 'anyOf'.
You can combine conditions inside 'when' using 'allOf' (AND) or 'anyOf' (OR). Example: when { allOf { branch 'main' environment name: 'DEPLOY', value: 'true' } } This runs only if branch is 'main' AND DEPLOY variable is 'true'.
Result
Stage runs only when all specified conditions are met.
Combining conditions lets you create precise rules for stage execution.
4
IntermediateUsing Expression Conditions in when
🤔Before reading on: do you think 'expression' conditions can use any Groovy code or only simple checks? Commit to your answer.
Concept: Use Groovy expressions inside 'when' to create custom conditions.
The 'expression' condition lets you write Groovy code that returns true or false. Example: when { expression { return env.BRANCH_NAME == 'develop' && currentBuild.number % 2 == 0 } } This runs the stage only on 'develop' branch and even build numbers.
Result
Stage runs only when the custom Groovy expression evaluates to true.
Expression conditions give you full flexibility to decide stage execution.
5
AdvancedSkipping Stages with when and Post Actions
🤔Before reading on: do you think skipped stages run their post actions or not? Commit to your answer.
Concept: Understand how skipped stages behave and how post actions run.
When a stage is skipped due to 'when', its steps do not run. However, post actions like 'always' or 'success' still run unless the stage is completely skipped. Example: stage('Deploy') { when { branch 'main' } steps { echo 'Deploying...' } post { always { echo 'Cleanup' } } } If branch is not 'main', steps skip but 'Cleanup' runs.
Result
Post actions run even if the stage steps are skipped.
Knowing this helps you handle cleanup or notifications reliably.
6
ExpertPerformance and Pitfalls of Complex when Conditions
🤔Before reading on: do you think complex 'when' expressions slow down the pipeline significantly? Commit to your answer.
Concept: Explore how complex 'when' conditions affect pipeline performance and reliability.
Complex 'when' expressions, especially those calling external scripts or APIs, can slow down pipeline startup. Also, errors in expressions can cause stage failures or unexpected skips. Best practice is to keep 'when' conditions simple and test them thoroughly. Use caching or environment variables to avoid repeated expensive checks.
Result
Pipelines run faster and more reliably with well-designed 'when' conditions.
Understanding performance impact prevents slow or flaky pipelines in production.
Under the Hood
The 'when' directive is evaluated by the Jenkins pipeline engine before running a stage. It checks the specified conditions using Groovy code and Jenkins environment variables. If the conditions return true, the stage runs; otherwise, it is skipped. This evaluation happens during the pipeline's execution planning phase, allowing Jenkins to skip unnecessary work early.
Why designed this way?
The 'when' directive was designed to optimize pipeline execution by avoiding unnecessary stages. Early Jenkins pipelines ran all stages regardless of context, wasting resources. Introducing 'when' allowed conditional logic without complex scripting, making pipelines easier to write and maintain. The design balances flexibility with simplicity by using declarative syntax and Groovy expressions.
Pipeline Execution Flow
┌───────────────┐
│ Start Pipeline│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Evaluate Stage │
│  'when' cond. │
└──────┬────────┘
       │true
       ▼
┌───────────────┐
│   Run Stage   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│  Post Actions │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Next Stage or │
│   Pipeline End│
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does a stage with a false 'when' condition run its steps or skip them? Commit to yes or no.
Common Belief:If a stage's 'when' condition is false, the stage still runs but skips steps.
Tap to reveal reality
Reality:The entire stage is skipped, including all steps; they do not run at all.
Why it matters:Thinking steps run can cause confusion when expected actions don't happen, leading to debugging delays.
Quick: Can 'when' conditions access environment variables set in previous stages? Commit to yes or no.
Common Belief:Yes, 'when' conditions can use environment variables set earlier in the pipeline.
Tap to reveal reality
Reality:No, 'when' conditions are evaluated before stage execution, so environment variables set in previous stages are not available.
Why it matters:Relying on unavailable variables causes conditions to fail unexpectedly, breaking pipeline logic.
Quick: Does combining multiple 'when' conditions with 'allOf' mean the stage runs if any condition is true? Commit to yes or no.
Common Belief:Yes, 'allOf' runs the stage if any condition is true.
Tap to reveal reality
Reality:'allOf' requires all conditions to be true; if any is false, the stage is skipped.
Why it matters:Misunderstanding this leads to stages not running when expected, causing build failures.
Quick: Can complex Groovy expressions in 'when' cause pipeline failures? Commit to yes or no.
Common Belief:No, 'when' expressions are always safe and won't cause failures.
Tap to reveal reality
Reality:Yes, errors in Groovy expressions can cause the pipeline to fail or skip stages unexpectedly.
Why it matters:Ignoring this can cause hard-to-debug pipeline crashes and unreliable builds.
Expert Zone
1
The 'when' directive evaluates conditions before the stage runs, so it cannot depend on runtime data generated inside the stage.
2
Using 'expression' conditions allows powerful logic but requires careful error handling to avoid pipeline failures.
3
Post actions run even if the stage is skipped, enabling reliable cleanup or notifications regardless of stage execution.
When NOT to use
Avoid using 'when' for complex runtime decisions that depend on data generated during the stage. Instead, use scripted pipelines or conditional steps inside the stage. Also, do not rely on 'when' for controlling parallel branch execution; use parallel stage constructs instead.
Production Patterns
In production, 'when' is used to run deployment stages only on specific branches or tags, skip tests on documentation-only changes, or run expensive steps conditionally. Teams often combine 'when' with environment variables and parameters to create flexible pipelines that adapt to different workflows.
Connections
Feature Flags in Software Development
Both control execution flow based on conditions to enable or disable features or stages.
Understanding conditional execution in Jenkins pipelines helps grasp how feature flags toggle functionality dynamically in applications.
Traffic Control Systems
The 'when' directive acts like a traffic signal controlling flow based on rules, similar to traffic lights managing vehicle movement.
Recognizing this control mechanism clarifies how pipelines optimize resource use by allowing or blocking stages.
Decision Trees in Machine Learning
Both use conditions to decide paths or actions based on input data.
Seeing 'when' as a decision node helps understand how pipelines branch and adapt to different scenarios.
Common Pitfalls
#1Using environment variables set inside a stage in a 'when' condition.
Wrong approach:stage('Deploy') { when { environment name: 'MY_VAR', value: 'true' } steps { echo 'Deploying...' } } // MY_VAR is set in a previous stage's steps
Correct approach:stage('Deploy') { when { expression { return env.MY_VAR == 'true' } } steps { echo 'Deploying...' } } // MY_VAR must be set before pipeline starts or passed as parameter
Root cause:Misunderstanding that 'when' conditions are evaluated before stage execution, so variables set during the pipeline are not yet available.
#2Combining multiple conditions without proper 'allOf' or 'anyOf' blocks.
Wrong approach:when { branch 'main' environment name: 'DEPLOY', value: 'true' } // This is invalid syntax
Correct approach:when { allOf { branch 'main' environment name: 'DEPLOY', value: 'true' } } // Correctly combines conditions with AND logic
Root cause:Not using the required syntax to combine multiple conditions, causing pipeline syntax errors.
#3Writing complex Groovy expressions in 'when' without error handling.
Wrong approach:when { expression { return someUndefinedVariable == true } } // Causes pipeline failure if variable is undefined
Correct approach:when { expression { return binding.hasVariable('someDefinedVariable') && someDefinedVariable == true } } // Safely checks variable existence before use
Root cause:Not anticipating runtime errors in Groovy expressions, leading to pipeline crashes.
Key Takeaways
The 'when' directive controls whether a Jenkins pipeline stage runs based on conditions, saving time and resources.
Conditions can be simple like branch names or complex Groovy expressions, combined with logical operators for precision.
'When' conditions are evaluated before stage execution, so they cannot use variables set during the pipeline run.
Post actions run even if a stage is skipped, allowing reliable cleanup and notifications.
Careful design of 'when' conditions prevents pipeline failures and improves build efficiency in real-world projects.