Skip to content
Latchkey

How to Deploy Only From the Main Branch in Jenkins

A when { branch "main" } guard skips the deploy stage on every branch except main.

Keep build and test stages unconditional, then add when { branch "main" } to the deploy stage so feature branches build but never deploy.

Steps

  • Leave build and test stages without a when so all branches run them.
  • Add when { branch "main" } to the deploy stage.
  • On other branches the deploy stage is skipped, not failed.

Pipeline

Jenkinsfile
pipeline {
  agent any
  stages {
    stage('Test') { steps { sh 'make test' } }
    stage('Deploy') {
      when { branch 'main' }
      steps { sh './deploy.sh' }
    }
  }
}

Gotchas

  • The branch condition matches the SCM branch, available in Multibranch and most SCM-backed jobs.
  • For a freestyle single-branch job use when { expression { env.GIT_BRANCH == 'origin/main' } }.

Related guides

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