Search code examples
jenkinsgroovycontinuous-integrationjenkins-pipeline

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


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


Solution

  • With this issue resolved, you can now do this:

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