Skip to main content

Working with Conditional Logic

1. Using When Directive

Property Description Values Notes
when Conditional block to control execution flow branch, environment, expression Used in Jenkins Pipeline syntax to conditionally execute stages or steps

Example: Using when with branch condition

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
        stage('Deploy') {
            when {
                branch 'main'
            }
            steps {
                echo 'Deploying to production...'
            }
        }
    }
}

Example: Using when with environment variable

pipeline {
    agent any
    stages {
        stage('Test') {
            when {
                environment name: 'ENVIRONMENT', value: 'staging'
            }
            steps {
                echo 'Running tests in staging...'
            }
        }
    }
}

Example: Using when with expression

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                script {
                    def buildNumber = env.BUILD_NUMBER
                    echo "Build number is ${buildNumber}"
                }
            }
        }
        stage('Deploy') {
            when {
                expression { env.BUILD_NUMBER >= 10 }
            }
            steps {
                echo 'Deploying to production...'
            }
        }
    }
}

2. Using When with Environment Conditions

Property Description Values Notes
when Condition to evaluate before executing the block environment Used to conditionally execute stages based on environment variables

Example: Using when with environment conditions

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
        stage('Deploy') {
            when {
                environment name: 'ENVIRONMENT', value: 'production'
            }
            steps {
                echo 'Deploying to production...'
            }
        }
    }
}

3. Using When with ChangeRequest

Property Description Values Notes
changeRequest() Triggers the pipeline when a change request is created or updated changeRequest() Used in when conditions to control pipeline execution based on change requests

Example: Using changeRequest in a Pipeline

pipeline {
    agent any
    stages {
        stage('Build') {
            when {
                changeRequest()
            }
            steps {
                echo 'Running build for change request'
            }
        }
    }
}
Note: The changeRequest() condition requires the Jenkins Pipeline Model Definition plugin to be installed and configured.

4. Using When with Tag Conditions

Condition Description Usage
branch Triggers the pipeline when a build is triggered on a specific branch. when { branch 'main' }
tag Triggers the pipeline when a build is triggered on a specific tag. when { tag 'v1.0' }
environment Triggers the pipeline when an environment variable matches a specific value. when { environment name: 'ENV', value: 'production' }
not Negates a condition. when { not { branch 'develop' } }
allOf Triggers the pipeline when all specified conditions are met. when { allOf { branch 'main'; environment name: 'ENV', value: 'production' } }
anyOf Triggers the pipeline when any of the specified conditions are met. when { anyOf { branch 'main'; branch 'develop' } }

Example: Using Tag Conditions in a Pipeline

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
    }
    post {
        success {
            when {
                tag 'v*'
            }
            echo 'Tagged build succeeded'
        }
    }
}
Note: The tag condition can use wildcards like v* to match tags that start with "v".

5. Using AllOf and AnyOf Conditions

The allOf and anyOf conditions in Jenkins are used to combine multiple conditions with logical AND and OR operations respectively. These conditions are particularly useful in pipeline scripts to control execution flow based on complex criteria.

Condition Description Usage Example
allOf Executes the block only if ALL conditions inside it evaluate to true.
when {
    allOf {
        branch 'main'
        environment name: 'BUILD_TYPE', value: 'production'
    }
}
anyOf Executes the block if ANY of the conditions inside it evaluate to true.
when {
    anyOf {
        branch 'feature/*'
        environment name: 'BUILD_TYPE', value: 'staging'
    }
}

Example: Using allOf in a Pipeline

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
            when {
                allOf {
                    branch 'main'
                    environment name: 'BUILD_TYPE', value: 'production'
                }
            }
        }
    }
}

Example: Using anyOf in a Pipeline

pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps {
                echo 'Deploying...'
            }
            when {
                anyOf {
                    branch 'release/*'
                    environment name: 'BUILD_TYPE', value: 'staging'
                }
            }
        }
    }
}

6. Using Not Condition

Property Values Description
not condition Negates the given condition

Example: Using not condition in Jenkins Pipeline

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                script {
                    if (not { env.BRANCH_NAME == 'main' }) {
                        echo 'This runs when not on main branch'
                    }
                }
            }
        }
    }
}

7. Using Triggering Cause Conditions

Condition Description Usage
SCM polling Triggers a build when changes are detected in the source control management system. scm
Remote trigger Triggers a build when a remote system sends a request to Jenkins. remoteTrigger
Timer Triggers a build at specified intervals or times. timer
Upstream build Triggers a build when an upstream project completes successfully. upstream
Manual trigger Triggers a build manually by user action. manual

Example: SCM Polling Configuration

triggers {
    scm('H/5 * * * *')
}

Example: Timer Trigger

triggers {
    timer('H 0 * * *')
}

8. Using Custom Expressions

Custom expressions in Jenkins allow you to define complex conditional logic using Groovy scripting within pipelines. These expressions are evaluated at runtime and can be used in various conditional directives like when, if, and else.

Expression Type Description Example
Groovy Expression Allows full Groovy scripting for complex conditions expression { return env.BRANCH_NAME == 'main' }
Scripted Pipeline Use scripted pipeline syntax for complex logic
when {
    expression {
        return params.buildType == 'release'
    }
}

Example: Custom Expression in Pipeline

pipeline {
    agent any
    stages {
        stage('Build') {
            when {
                expression {
                    return env.BRANCH_NAME == 'main' && env.GIT_COMMIT != null
                }
            }
            steps {
                echo 'Running on main branch'
            }
        }
    }
}
Note: Custom expressions are evaluated in the context of the Jenkins pipeline and have access to all environment variables, parameters, and built-in functions.

9. Combining Multiple Conditions

Operator Description Example Notes
&& Logical AND if (condition1 && condition2) { ... } Both conditions must be true
|| Logical OR if (condition1 || condition2) { ... } At least one condition must be true
! Logical NOT if (!condition) { ... } Negates the condition
! Logical NOT if (!condition) { ... } Negates the condition

Example: Combining Conditions in Jenkins Pipeline

pipeline {
    agent any
    stages {
        stage('Build') {
            when {
                allOf {
                    branch 'main'
                    environment name: 'ENV', value: 'production'
                }
            }
            steps {
                echo 'Building...'
            }
        }
    }
}

Example: Using OR Logic in Jenkins Pipeline

pipeline {
    agent any
    stages {
        stage('Deploy') {
            when {
                anyOf {
                    branch 'feature/*'
                    environment name: 'DEPLOY', value: 'true'
                }
            }
            steps {
                echo 'Deploying...'
            }
        }
    }
}

10. Using BeforeAgent Option

Property Description Values Notes
beforeAgent Defines steps to run before the agent block true or false Defaults to false. When set to true, steps run in the main node before any agent is allocated.

Example: beforeAgent usage in Jenkinsfile

pipeline {
    agent any
    beforeAgent true
    stages {
        stage('Setup') {
            steps {
                echo 'Running setup before agent allocation'
            }
        }
    }
}
Note: The beforeAgent option is useful for running setup or environment checks before any agent is allocated, which can save resources and improve pipeline efficiency.

Was this article helpful?