How to specify when branch NOT (branch name) in jenkinsfile?

HosseinK picture HosseinK · Apr 24, 2017 · Viewed 40.6k times · Source

How can I specify something like the following in my Jenkinsfile?

when branch not x

I know how to specify branch specific tasks like:

stage('Master Branch Tasks') {
        when {
            branch "master"
        }
        steps {
          sh '''#!/bin/bash -l
          Do some stuff here
          '''
        }
}

However I'd like to specify a stage for when branch is not master or staging like the following:

stage('Example') {
    if (env.BRANCH_NAME != 'master' && env.BRANCH_NAME != 'staging') {
        echo 'This is not master or staging'
    } else {
        echo 'things and stuff'
    }
}

However the above does not work and fails with the following errors:

WorkflowScript: 62: Not a valid stage section definition: "if 

WorkflowScript: 62: Nothing to execute within stage "Example" 

Note source for my failed try: https://jenkins.io/doc/book/pipeline/syntax/#flow-control

Answer

Zac Kwan picture Zac Kwan · Jul 10, 2017

With this issue resolved, you can now do this:

stage('Example (Not master)') {
   when {
       not {
           branch 'master'
       }
   }
   steps {
     sh 'do-non-master.sh'
   }
}