Bird
Raised Fist0
Jenkinsdevops~5 mins

Stage conditions with when directive in Jenkins - Commands & Configuration

Choose your learning style10 modes available
Introduction
Sometimes you want parts of your Jenkins pipeline to run only if certain things are true. The when directive helps you decide if a stage should run or be skipped based on conditions.
When you want to run tests only on the main branch but skip on others
When you want to deploy only if the build was successful
When you want to run a stage only during working hours
When you want to skip a stage if a certain file hasn't changed
When you want to run a stage only if an environment variable has a specific value
Config File - Jenkinsfile
Jenkinsfile
pipeline {
  agent any
  stages {
    stage('Build') {
      steps {
        echo 'Building...'
      }
    }
    stage('Test') {
      when {
        branch 'main'
      }
      steps {
        echo 'Testing on main branch only'
      }
    }
    stage('Deploy') {
      when {
        expression { return currentBuild.result == null || currentBuild.result == 'SUCCESS' }
      }
      steps {
        echo 'Deploying only if build succeeded'
      }
    }
  }
}

This Jenkinsfile defines a pipeline with three stages: Build, Test, and Deploy.

The when directive in the Test stage ensures it runs only on the 'main' branch.

The Deploy stage uses an expression condition to run only if the build succeeded or has no result yet.

Commands
This command updates the Jenkins pipeline with the Jenkinsfile containing the when conditions to control stage execution.
Terminal
jenkins-jobs --conf jenkins.ini update Jenkinsfile
Expected OutputExpected
Job updated successfully
Starts the Jenkins pipeline job named 'my-pipeline' to run the stages with the when conditions applied.
Terminal
jenkins-cli build my-pipeline
Expected OutputExpected
[Pipeline] Start of Pipeline [Pipeline] stage [Pipeline] { (Build) Building... [Pipeline] } [Pipeline] // stage [Pipeline] stage [Pipeline] { (Test) Testing on main branch only [Pipeline] } [Pipeline] // stage [Pipeline] stage [Pipeline] { (Deploy) Deploying only if build succeeded [Pipeline] } [Pipeline] // stage [Pipeline] End of Pipeline Finished: SUCCESS
Shows the console output of the last run of the 'my-pipeline' job to verify which stages ran based on the when conditions.
Terminal
jenkins-cli console my-pipeline
Expected OutputExpected
[Pipeline] Start of Pipeline [Pipeline] stage [Pipeline] { (Build) Building... [Pipeline] } [Pipeline] // stage [Pipeline] stage [Pipeline] { (Test) Testing on main branch only [Pipeline] } [Pipeline] // stage [Pipeline] stage [Pipeline] { (Deploy) Deploying only if build succeeded [Pipeline] } [Pipeline] // stage [Pipeline] End of Pipeline Finished: SUCCESS
Key Concept

If you remember nothing else from this pattern, remember: the when directive controls if a stage runs by checking simple conditions like branch name or build status.

Common Mistakes
Using when conditions without proper syntax like missing braces or quotes
Jenkins will fail to parse the Jenkinsfile and the pipeline won't run
Always use correct syntax, for example: when { branch 'main' } or when { expression { return true } }
Expecting stages to run when conditions are false
Stages with when conditions that evaluate to false are skipped and do not run
Design your pipeline knowing that when conditions skip stages if false
Using currentBuild.result in when expression without checking for null
If currentBuild.result is null (build in progress), the expression may fail or behave unexpectedly
Check for null explicitly like: currentBuild.result == null || currentBuild.result == 'SUCCESS'
Summary
Use the when directive in Jenkinsfile stages to run them conditionally.
Common conditions include branch name and build success status.
Run the pipeline and check console output to verify which stages executed.

Practice

(1/5)
1. What is the main purpose of the when directive in a Jenkins pipeline stage?
easy
A. To set the timeout for a stage execution
B. To define environment variables for a stage
C. To specify the agent where the stage runs
D. To control whether a stage runs based on specified conditions

Solution

  1. Step 1: Understand the role of when directive

    The when directive is used to decide if a stage should run or be skipped based on conditions.
  2. Step 2: Compare with other stage directives

    Other directives like environment, agent, and timeout serve different purposes unrelated to conditional execution.
  3. Final Answer:

    To control whether a stage runs based on specified conditions -> Option D
  4. Quick Check:

    when controls stage execution [OK]
Hint: Remember: when decides if stage runs or skips [OK]
Common Mistakes:
  • Confusing when with environment
  • Thinking when sets agent or timeout
  • Assuming when always runs the stage
2. Which of the following is the correct syntax to run a stage only on the 'main' branch using the when directive?
easy
A.
when {
  branch 'main'
}
B.
when {
  branch == 'main'
}
C.
when {
  if (branch == 'main')
}
D.
when {
  branch: 'main'
}

Solution

  1. Step 1: Recall correct when syntax for branch condition

    The correct syntax uses branch 'branchName' inside when block without operators or colons.
  2. Step 2: Identify syntax errors in other options

    Options B and C use invalid operators or expressions; D uses colon which is incorrect in this context.
  3. Final Answer:

    when { branch 'main' } -> Option A
  4. Quick Check:

    Use branch 'name' syntax [OK]
Hint: Use branch 'name' without operators in when [OK]
Common Mistakes:
  • Using comparison operators inside when
  • Adding colons or equal signs incorrectly
  • Writing if statements inside when
3. Given the following Jenkins pipeline snippet, what will happen if the branch is 'feature'?
stage('Deploy') {
  when {
    branch 'main'
  }
  steps {
    echo 'Deploying to production'
  }
}
medium
A. The stage will run and print 'Deploying to production'
B. The stage will be skipped and nothing will print
C. The pipeline will fail with a syntax error
D. The stage will run but print nothing

Solution

  1. Step 1: Understand the when condition

    The stage runs only if the branch is 'main'. Since the branch is 'feature', the condition is false.
  2. Step 2: Determine stage behavior on false condition

    When when condition is false, Jenkins skips the stage and does not execute steps.
  3. Final Answer:

    The stage will be skipped and nothing will print -> Option B
  4. Quick Check:

    Branch mismatch skips stage [OK]
Hint: If branch doesn't match, stage is skipped silently [OK]
Common Mistakes:
  • Assuming stage runs regardless of branch
  • Expecting syntax error for valid when
  • Thinking stage runs but steps don't print
4. Identify the error in this Jenkins pipeline stage that uses when:
stage('Test') {
  when {
    branch == 'dev'
  }
  steps {
    echo 'Running tests'
  }
}
medium
A. The stage name 'Test' is not allowed
B. Missing agent directive for the stage
C. Using '==' operator inside when is invalid syntax
D. The steps block should be inside when

Solution

  1. Step 1: Check when syntax for branch condition

    The when directive expects branch 'name' without operators like '=='.
  2. Step 2: Validate other parts of the stage

    Missing agent is allowed if inherited; steps must be outside when; stage name is valid.
  3. Final Answer:

    Using '==' operator inside when is invalid syntax -> Option C
  4. Quick Check:

    No operators in when branch condition [OK]
Hint: No operators like '==' inside when branch check [OK]
Common Mistakes:
  • Using comparison operators inside when
  • Placing steps inside when
  • Assuming stage name restrictions
5. You want a Jenkins stage to run only when the branch is 'release' and an environment variable DEPLOY is set to 'true'. Which when directive correctly implements this?
hard
A.
when {
  allOf {
    branch 'release'
    environment name: 'DEPLOY', value: 'true'
  }
}
B.
when {
  branch 'release' && environment name: 'DEPLOY', value: 'true'
}
C.
when {
  branch 'release'
  environment 'DEPLOY': 'true'
}
D.
when {
  anyOf {
    branch 'release'
    environment name: 'DEPLOY', value: 'true'
  }
}

Solution

  1. Step 1: Understand combining conditions in when

    To require both conditions, use allOf block combining branch and environment.
  2. Step 2: Analyze each option's logic

    when {
      allOf {
        branch 'release'
        environment name: 'DEPLOY', value: 'true'
      }
    }
    correctly uses allOf.
    when {
      branch 'release' && environment name: 'DEPLOY', value: 'true'
    }
    uses invalid syntax with '&&'.
    when {
      branch 'release'
      environment 'DEPLOY': 'true'
    }
    uses invalid syntax for environment condition (missing name: and value:).
    when {
      anyOf {
        branch 'release'
        environment name: 'DEPLOY', value: 'true'
      }
    }
    uses anyOf, meaning either condition suffices.
  3. Final Answer:

    when { allOf { branch 'release' environment name: 'DEPLOY', value: 'true' } } -> Option A
  4. Quick Check:

    Use allOf to combine multiple when conditions [OK]
Hint: Use allOf to require all conditions true [OK]
Common Mistakes:
  • Using '&&' inside when block
  • Using environment 'VAR': 'value' shorthand syntax
  • Using anyOf when all conditions are needed
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard