0
0
Jenkinsdevops~10 mins

Stage conditions with when directive in Jenkins - Step-by-Step Execution

Choose your learning style9 modes available
Process Flow - Stage conditions with when directive
Start Pipeline
Enter Stage
Evaluate 'when' Condition
Run Stage Steps
Stage Complete
Next Stage or End
The pipeline starts and enters a stage. The 'when' condition is checked. If true, the stage runs; if false, it skips.
Execution Sample
Jenkins
pipeline {
  agent any
  stages {
    stage('Build') {
      when { branch 'main' }
      steps { echo 'Building...' }
    }
  }
}
This pipeline runs the 'Build' stage only if the branch is 'main'.
Process Table
StepActionCondition EvaluatedCondition ResultStage ActionOutput
1Start pipelineN/AN/APipeline startsPipeline started
2Enter 'Build' stagebranch == 'main'?TrueRun stage stepsEcho: Building...
3Complete 'Build' stageN/AN/AStage completeStage 'Build' finished
4Pipeline endsN/AN/APipeline completePipeline finished
💡 Pipeline ends after all stages processed
Status Tracker
VariableStartAfter Step 2After Step 3Final
branchmainmainmainmain
when condition (branch=='main')N/ATrueTrueTrue
stage statusNot startedRunningCompletedCompleted
Key Moments - 2 Insights
Why does the stage run only when the branch is 'main'?
Because the 'when' directive checks if the branch equals 'main' (see execution_table step 2). If false, the stage would skip.
What happens if the 'when' condition is false?
The stage is skipped entirely, no steps run (not shown here but implied by the 'No' branch in concept_flow).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the condition result at step 2?
AFalse
BN/A
CTrue
DError
💡 Hint
Check the 'Condition Result' column at step 2 in the execution_table.
At which step does the stage complete?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the 'Stage Action' column for when the stage finishes.
If the branch was 'feature', what would happen to the stage?
AStage is skipped
BPipeline fails
CStage runs normally
DStage runs twice
💡 Hint
Refer to concept_flow where 'when' condition false leads to skipping the stage.
Concept Snapshot
Jenkins 'when' directive controls stage execution.
Syntax: when { condition }
If condition true, stage runs; else skipped.
Common conditions: branch, environment, expression.
Use to run stages selectively based on context.
Full Transcript
This visual execution shows how Jenkins pipeline stages use the 'when' directive to decide if they run. The pipeline starts, enters a stage, and evaluates the 'when' condition. If the condition is true, the stage steps execute; if false, the stage is skipped. The example uses a branch condition to run the 'Build' stage only on the 'main' branch. Variables like branch and stage status change as the pipeline progresses. Key moments clarify why stages run or skip based on the condition. Quiz questions test understanding of condition results and stage flow.