7. When

7.1. Branch

  • branch()

  • Execute the stage when the branch being built matches the branch pattern given

  • Note that this only works on a multibranch Pipelnes

when {
    branch 'master'
}

7.2. Environment

  • environment()

  • Execute the stage when the specified environment variable is set to the given value

when {
    environment(name: 'DEPLOY_TO', value: 'production')
}

7.3. Expression

  • expression()

  • Execute the stage when the specified Groovy expression evaluates to true

when {
    expression { return params.DEBUG_BUILD }
}

7.4. Not

  • not()

  • Execute the stage when the nested condition is false. Must contain one condition

when {
    not { branch 'master' }
}

7.5. All of...

  • allOf()

  • Execute the stage when all of the nested conditions are true. Must contain at least one condition

when {
    allOf {
        branch 'master'
        environment(name: 'DEPLOY_TO', value: 'production')
    }
}

7.6. Any of...

  • anyOf()

  • Execute the stage when at least one of the nested conditions is true. Must contain at least one condition

when {
    anyOf {
        branch 'master'
        branch 'staging'
    }
}

7.7. Examples

7.7.1. Example 1

pipeline {
    agent any

    stages {
        stage('Test') {
            when {
                sh '/bin/echo Should I test?'
                return true
            }

            steps {
                sh '/bin/echo Testing...'
            }
        }
}

7.7.2. Example 2

pipeline {
    agent any

    stages {
        stage('Deploy') {
            when {
                expression {
                    BRANCH_NAME ==~ /(production|staging)/
                }

                anyOf {
                    environment name: 'DEPLOY_TO', value: 'production'
                    environment name: 'DEPLOY_TO', value: 'staging'
                }
            }

            steps {
                sh '/bin/echo Deploying...'
            }
        }
    }
}