Bird
Raised Fist0
Jenkinsdevops~5 mins

Conditional deployment logic in Jenkins - Commands & Configuration

Choose your learning style10 modes available
Introduction
Sometimes you want your deployment to happen only if certain conditions are met, like only deploying to production if tests pass. Conditional deployment logic helps you control when parts of your Jenkins pipeline run, so you avoid mistakes and save time.
When you want to deploy to production only if all tests succeed.
When you want to skip deployment on weekends or outside business hours.
When you want to deploy to different environments based on the branch name.
When you want to run deployment steps only if a specific file changed in the commit.
When you want to avoid deploying if a manual approval step was not confirmed.
Config File - Jenkinsfile
Jenkinsfile
pipeline {
  agent any
  environment {
    TEST_RESULT = ''
  }
  stages {
    stage('Build') {
      steps {
        echo 'Building the application'
      }
    }
    stage('Test') {
      steps {
        echo 'Running tests'
        script {
          // Simulate test result
          env.TEST_RESULT = 'SUCCESS'
        }
      }
    }
    stage('Deploy') {
      when {
        expression { env.TEST_RESULT == 'SUCCESS' }
      }
      steps {
        echo 'Deploying application because tests passed'
      }
    }
  }
}

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

The when block in the Deploy stage uses an expression condition to check if the tests passed by evaluating the environment variable TEST_RESULT. The Deploy stage runs only if this condition is true.

Commands
This command updates the Jenkins job configuration with the Jenkinsfile containing conditional deployment logic.
Terminal
jenkins-jobs --conf jenkins.ini update Jenkinsfile
Expected OutputExpected
Job updated successfully
This command triggers the Jenkins pipeline named 'my-pipeline' to start the build, test, and conditional deploy stages.
Terminal
jenkins-cli build my-pipeline
Expected OutputExpected
[Pipeline] Start of Pipeline [Pipeline] stage [Pipeline] { (Build) [Pipeline] echo Building the application [Pipeline] } [Pipeline] stage [Pipeline] { (Test) [Pipeline] echo Running tests [Pipeline] script [Pipeline] } [Pipeline] stage [Pipeline] { (Deploy) [Pipeline] echo Deploying application because tests passed [Pipeline] } [Pipeline] End of Pipeline Finished: SUCCESS
This command fetches the console output of the last run of the 'my-pipeline' job to verify the conditional deployment executed.
Terminal
jenkins-cli console my-pipeline
Expected OutputExpected
Building the application Running tests Deploying application because tests passed
Key Concept

If you remember nothing else from this pattern, remember: Jenkins 'when' blocks let you run pipeline stages only when specific conditions are true.

Common Mistakes
Not setting or exporting the environment variable used in the 'when' condition.
The 'when' expression will always evaluate to false or error, so the deployment stage never runs.
Set the environment variable inside a 'script' block before the 'when' condition is evaluated.
Using 'when' conditions with syntax errors or unsupported expressions.
Jenkins pipeline will fail to parse or run the pipeline, causing build errors.
Use valid Groovy expressions inside 'when { expression { ... } }' and test them carefully.
Summary
Define deployment conditions inside the 'when' block of a Jenkins pipeline stage.
Use environment variables or Groovy expressions to control if deployment runs.
Trigger the pipeline and check console output to confirm conditional deployment.

Practice

(1/5)
1. What is the main purpose of using a when block in a Jenkins pipeline?
easy
A. To define environment variables for the pipeline
B. To run a stage only if certain conditions are met
C. To specify the agent where the pipeline runs
D. To declare pipeline parameters

Solution

  1. Step 1: Understand the role of when in Jenkins

    The when block controls whether a stage runs based on conditions.
  2. Step 2: Compare options with when usage

    Only To run a stage only if certain conditions are met describes conditional execution, which matches when functionality.
  3. Final Answer:

    To run a stage only if certain conditions are met -> Option B
  4. Quick Check:

    when controls stage execution = A [OK]
Hint: Remember: when means "only if" for stages [OK]
Common Mistakes:
  • Confusing when with environment setup
  • Thinking when sets agents
  • Assuming when declares parameters
2. Which of the following is the correct syntax to run a stage only on the 'main' branch in a declarative Jenkins pipeline?
easy
A. when { branch is 'main' }
B. when { branch == 'main' }
C. when { branch 'main' }
D. when { branch equals 'main' }

Solution

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

    The correct syntax uses branch 'main' inside when block.
  2. Step 2: Check each option's syntax

    Only when { branch 'main' } matches Jenkins declarative syntax; others use invalid expressions.
  3. Final Answer:

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

    Correct branch syntax = C [OK]
Hint: Use branch 'name' exactly inside when [OK]
Common Mistakes:
  • Using comparison operators inside when
  • Writing invalid expressions like 'branch =='
  • Confusing Groovy syntax with declarative syntax
3. Given this Jenkins pipeline snippet, what will happen if the branch is 'develop'?
stage('Deploy') {
  when {
    branch 'main'
  }
  steps {
    echo 'Deploying to production'
  }
}
medium
A. The stage will be skipped and nothing prints
B. The stage will run and print 'Deploying to production'
C. The pipeline will fail with a syntax error
D. The stage will run but print nothing

Solution

  1. Step 1: Analyze the when condition

    The stage runs only if branch is 'main'. Here branch is 'develop', so condition fails.
  2. Step 2: Determine stage behavior on condition failure

    When when condition fails, the stage is skipped and no steps run.
  3. Final Answer:

    The stage will be skipped and nothing prints -> Option A
  4. Quick Check:

    Branch mismatch skips stage = A [OK]
Hint: If branch doesn't match when, stage skips silently [OK]
Common Mistakes:
  • Assuming stage runs anyway
  • Expecting error on branch mismatch
  • Thinking stage runs but prints nothing
4. Identify the error in this Jenkins pipeline snippet that tries to deploy only if environment variable DEPLOY is 'true':
stage('Deploy') {
  when {
    environment DEPLOY == 'true'
  }
  steps {
    echo 'Deploying application'
  }
}
medium
A. The stage name cannot be 'Deploy'
B. The when block must be inside steps
C. The echo command is not allowed in steps
D. The environment condition is invalid syntax

Solution

  1. Step 1: Check when syntax for environment variable

    The correct syntax uses environment name: 'DEPLOY', value: 'true' or expression blocks, not direct comparison.
  2. Step 2: Identify invalid usage

    Using environment DEPLOY == 'true' is invalid and causes syntax error.
  3. Final Answer:

    The environment condition is invalid syntax -> Option D
  4. Quick Check:

    Invalid environment condition syntax = D [OK]
Hint: Use correct when { environment name: 'VAR', value: 'val' } syntax [OK]
Common Mistakes:
  • Writing direct comparisons inside when
  • Placing when inside steps
  • Misusing stage names
5. You want to deploy only if the branch is 'release' and the environment variable DEPLOY is 'yes'. Which when block correctly implements this in a declarative Jenkins pipeline?
hard
A. when { allOf { branch 'release'; environment name: 'DEPLOY', value: 'yes' } }
B. when { branch 'release' && environment DEPLOY == 'yes' }
C. when { branch 'release' environment DEPLOY == 'yes' }
D. when { anyOf { branch 'release'; environment name: 'DEPLOY', value: 'yes' } }

Solution

  1. Step 1: Understand combining conditions in when

    Use allOf to require both conditions true simultaneously.
  2. Step 2: Check syntax for branch and environment conditions

    when { allOf { branch 'release'; environment name: 'DEPLOY', value: 'yes' } } correctly uses allOf with branch 'release' and environment name: 'DEPLOY', value: 'yes'.
  3. Step 3: Identify errors in other options

    Options A and C use invalid syntax; D uses anyOf which means either condition, not both.
  4. Final Answer:

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

    Use allOf for AND conditions = B [OK]
Hint: Use allOf to combine multiple when conditions [OK]
Common Mistakes:
  • Using anyOf instead of allOf
  • Writing invalid combined expressions
  • Misusing environment condition syntax
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