Skip to content
Latchkey

How to Run a Stage Only on a Branch Pattern in a Jenkins Pipeline

The when { branch } condition gates a stage to matching branches using a glob or regex comparator.

Use when { branch pattern: ..., comparator: ... } to run a stage only on matching branches. Combine patterns with anyOf for several allowed branches.

Gate a stage to release branches

The deploy stage runs only on main or any release/* branch via a regex comparator.

Jenkinsfile
pipeline {
  agent any
  stages {
    stage('Deploy') {
      when {
        anyOf {
          branch 'main'
          branch pattern: 'release/.*', comparator: 'REGEXP'
        }
      }
      steps {
        sh './deploy.sh'
      }
    }
  }
}

Gotchas

  • env.BRANCH_NAME is only populated in multibranch pipelines; in a plain pipeline job when { branch } has nothing to match.
  • The default comparator is GLOB; set comparator: 'REGEXP' for real regex patterns.
  • Use anyOf/allOf to combine multiple branch patterns or mix with other when conditions.

Related guides

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