Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 957
HosseinK Avatar asked Apr 24 '17 01:04

HosseinK


People also ask

How do I mention a branch name in Jenkins?

How do I access the branch name causing this build from the Jenkinsfile? which is always master . If you are using GitHub Pull Request Builder plugin, you can use ${env. ghprbSourceBranch} or even ${env.

How do I select a branch in Jenkins pipeline?

Head over to your Jenkins instance and create a new item. Enter a name for the job, and select the “Multibranch Pipeline” option at the end of the screen. Then, click on the OK button. In the next screen, go to the “Branch sources” tab, click on the “Add source” button, and choose “Git” from the dropdown menu.

Is it impossible to checkout a different branch in Jenkinsfile?

@swoop81 answer is working but if you just want to checkout one branch, you could fetch only this one.

What types of syntax are used to define a Jenkinsfile?

A Jenkinsfile can be written using two types of syntax - Declarative and Scripted.


1 Answers

With this issue resolved, you can now do this:

stage('Example (Not master)') {    when {        not {            branch 'master'        }    }    steps {      sh 'do-non-master.sh'    } } 
like image 62
Zac Kwan Avatar answered Sep 20 '22 15:09

Zac Kwan