when Conditions

Conditional Execution with when

when decides whether a stage runs. Its conditions include branch, tag, buildingTag, changeRequest (a pull request), changeset (files touched), changelog, environment, equals, expression and triggeredBy, combined with allOf, anyOf and not. The decl-when job, with agent none and a boolean parameter DEPLOY, runs a Test stage and then:

decl-when (excerpt): deploy only when askedGroovy
    stage('Deploy') {
      when {
        beforeAgent true
        allOf {
          expression { params.DEPLOY }
          anyOf { branch 'main'; environment name: 'JOB_NAME', value: 'decl-when' }
        }
      }
      agent { label 'linux' }
      steps { echo "Deploying build ${env.BUILD_NUMBER} from ${env.NODE_NAME}" }
    }
Output
[Pipeline] { (Deploy)
Stage "Deploy" skipped due to when conditional

That was build 1, with DEPLOY=false; build 2, with DEPLOY=true, printed "Deploying build 2 from agent-1". branch 'main' was false both times, since BRANCH_NAME exists only in multibranch jobs (Multibranch Pipeline). By default when runs after the stage's agent is allocated; beforeAgent true checks first, so a skipped stage never waits for an executor (beforeInput and beforeOptions do the same for input and options).