Master Jenkins From Beginner to Enterprise

Clear, interactive, and structured Jenkins lessons designed to take you from beginner to enterprise level.

Conditional Execution with when

Learn the concepts, syntax criteria, evaluation rules, and logical conditions required to dynamically skip or execute pipeline stages at runtime.

What is Conditional Execution with when?

In an automated workflow, not every stage needs to run during every execution pass. For example, you might want to run comprehensive integration tests only on code changes from the main branch, or deploy software packages exclusively when deploying to a Production environment. The when directive serves as a strict structural guard to enforce this conditional control logic cleanly.

Simple Definition: The when directive is a syntax guard block placed inside a specific stage that evaluates conditions (like branch names, parameters, or environment flags) to decide whether to skip or execute that stage's steps.

Built-in Condition Assertions

Jenkins provides several built-in conditional logic functions that can be used inside the directive block:

  • The `branch` Matcher: Restricts stage execution to code changes matching a specific branch name pattern (e.g., branch 'main' or wildcard matches like branch 'feature/*').
  • The `environment` Matcher: Evaluates active environment variables to execute stages only when variables match precise text targets (e.g., environment name: 'DEPLOY_STAGE', value: 'Production').
  • The `expression` Block: A loose programmatic container that allows developers to write custom Groovy logical evaluation scripts returning a standard true or false flag.
  • Logical Operators (`allOf`, `anyOf`, `not`): Combines multiple complex check gates together (e.g., using allOf to ensure both a branch matches AND a runtime checkbox toggle parameter evaluates to true).

Key Concepts

Agent Allocation Evaluation Timing

Understanding that, by default, Jenkins allocations an execution agent *before* checking the `when` condition. This behavior can be optimized by setting `beforeAgent true` to skip resource-heavy agent provisioning if the stage is skipped.

Clean Dashboard Stage Views

Recognizing that when a condition evaluates to false, Jenkins completely skips the step sequence and marks the stage column layout with a clean 'Skipped' milestone tag in the UI grid.

Practical Jenkins Example

The following full declarative pipeline configuration showcases how to implement string-based selection matching and expression-based toggles to restrict optional execution steps:

pipeline {
    agent any






































    parameters {
        choice(name: 'DEPLOY_ENV', choices: ['Development', 'Staging', 'Production'], description: 'Target deployment infrastructure node.')
        booleanParam(name: 'RUN_SMOKE_TESTS', defaultValue: true, description: 'Toggle check box to fire core validation tests.')
    }

    stages {
        stage('Compile Code Base') {
            steps {
                echo 'INFO: Executing mandatory project assembly code steps...'
                sh 'echo "Artifact output ready inside workspace root."'
            }
        }

        stage('Optional Smoke Testing') {
            // 1. Evaluate a simple boolean param condition logic gate
            when {
                expression { return params.RUN_SMOKE_TESTS }
            }
            steps {
                echo 'INFO: Initializing dynamic smoke test execution check passes...'
                sh 'echo "Smoke verification step passed cleanly."'
            }
        }

        stage('Production Deployment Gate') {
            // 2. Combining environment verification logic along with timing safety controls
            when {
                beforeAgent true
                environment name: 'params.DEPLOY_ENV', value: 'Production'
            }
            steps {
                echo 'WARNING: Pushing production deployment payload assets out to server clusters...'
                sh 'echo "Deployment routines fully finalized."'
            }
        }
    }
}

Practice Exercise: Instantiate and Test a Conditional Guard

Step-by-Step Task Sequence:
  1. Open the script block workspace of an active test pipeline or spin up a new Pipeline item from your dashboard interface portal.
  2. Copy-paste the complete practical declarative multi-stage conditional script provided in the example above into your editor and click Save.
  3. Click **Build Now** to register the initial configuration profile on the server. *Note: As with all parameters, the initial pass uses structural default configurations.*
  4. Click the newly updated **Build with Parameters** option link, select `Development` from the dropdown selector, uncheck the smoke tests box, and click **Build**.
  5. Open the current run's **Console Output** to verify the log lines, observing how Jenkins evaluates the condition guards and outputs statements that stages were skipped.

Summary

You have completed the Conditional Execution with when lesson. Continue through the syllabus to learn how to split and execute separate pipeline workloads simultaneously by exploring the Parallel Execution lesson.