74

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

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
HosseinK
  • 1,247
  • 4
  • 13
  • 18

4 Answers4

112

With this issue resolved, you can now do this:

stage('Example (Not master)') {
   when {
       not {
           branch 'master'
       }
   }
   steps {
     sh 'do-non-master.sh'
   }
}
Zac Kwan
  • 5,587
  • 4
  • 20
  • 27
65

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.

Giovanni Benussi
  • 3,102
  • 2
  • 28
  • 30
25

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'
            }
        }
    }
}
Philip
  • 2,959
  • 1
  • 17
  • 22
0

For those who want to use with env values and in case of declarative pipeline and you have dynamic branch fetching then you can define your own variables globally and use like below.[The variable "deployBranch" needs to be declared before pipeline and updated in a stage earlier to current stage or before using evaluation ]

            stage ('checkout-NonMaster') {
                when {
                    not {
                        environment(name: "deployBranch", value: "master")
                    }
                }
                steps {

                        <anything goes here like groovy code or shell commands>
                }
            }