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

JenkinsGroovyContinuous IntegrationJenkins Pipeline

Jenkins Problem Overview


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

Jenkins Solutions


Solution 1 - Jenkins

With this issue resolved, you can now do this:

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

Solution 2 - Jenkins

You can also specify multiple conditions (in this case branch names) using anyOf:

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

In this case do-non-master-nor-staging.sh will run on all branches except on master and staging.

You can read about built-in conditions and general pipeline syntax here.

Solution 3 - Jenkins

The link from your post shows an example with the scripted pipeline syntax. Your code uses the declarative pipeline syntax. To use the scripted pipeline within declarative you can use the script step.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHosseinKView Question on Stackoverflow
Solution 1 - JenkinsZac KwanView Answer on Stackoverflow
Solution 2 - JenkinsGiovanni BenussiView Answer on Stackoverflow
Solution 3 - JenkinsPhilipView Answer on Stackoverflow