Skip to content
Latchkey

How to Use when {} Conditions in a Jenkins Pipeline

The when {} directive runs a stage only when its condition matches: a branch, an env value, an expression, or a parameter.

Place when {} at the top of a stage. Conditions like branch, environment, expression, and allOf/anyOf decide whether the stage executes.

Conditional stage execution

The deploy stage runs only on the main branch and only when the deploy parameter is true.

Jenkinsfile
pipeline {
  agent any
  parameters {
    booleanParam(name: 'DEPLOY', defaultValue: false)
  }
  stages {
    stage('Deploy') {
      when {
        allOf {
          branch 'main'
          expression { return params.DEPLOY }
        }
      }
      steps {
        sh './deploy.sh'
      }
    }
  }
}

Gotchas

  • Combine conditions with allOf/anyOf; not {} inverts a condition.
  • branch only works on multibranch pipelines; for plain jobs use expression { env.BRANCH_NAME == 'main' }.
  • A skipped stage shows as not-run in the UI, not as failed.

Key takeaways

  • when {} gates a stage on branch, env, expression, or params.
  • Combine conditions with allOf, anyOf, and not.
  • branch needs a multibranch pipeline to evaluate.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →