Jenkinsfile and different strategies for branches

Krzysztof Krasoń picture Krzysztof Krasoń · Apr 19, 2016 · Viewed 44.7k times · Source

I'm trying to use Jenkins file for all our builds in Jenkins, and I have following problem. We basically have 3 kind of builds:

  • pull-request build - it will be merged to master after code review, and if build works
  • manual pull-request build - a build that does the same as above, but can be triggered manually by the user (e.g. in case we have some unstable test)
  • an initial continuous deliver pipeline - this will build the code, deploy to repository, install artifacts from repository on the target server and start the application there

How should I contain all of the above builds into a single Jenkinsfile. Right now the only idea I have is to make a giant if that will check which branch it is and will do the steps.

So I have two questions:

1. Is that appropriate way to do it in Jenkinsfile?

  1. How to get the name of currently executing branch in multi-branch job type?

For reference, here's my current Jenkinsfile:

def servers = ['server1', 'server2']

def version = "1.0.0-${env.BUILD_ID}"

stage 'Build, UT, IT'
node {
    checkout scm
    env.PATH = "${tool 'Maven'}/bin:${env.PATH}"
    withEnv(["PATH+MAVEN=${tool 'Maven'}/bin"]) {
        sh "mvn -e org.codehaus.mojo:versions-maven-plugin:2.1:set -DnewVersion=$version -DgenerateBackupPoms=false"
        sh 'mvn -e clean deploy'
        sh 'mvn -e scm:tag'
    }
}


def nodes = [:]
for (int i = 0; i < servers.size(); i++) {
    def server = servers.get(i)
    nodes["$server"] = {
        stage "Deploy to INT ($server)"
        node {
            sshagent(['SOME-ID']) {
                sh """
                ssh ${server}.example.com <<END
                hostname
                /apps/stop.sh
                yum  -y update-to my-app.noarch
                /apps/start.sh
                END""".stripIndent()
            }
        }
    }
}

parallel nodes

EDIT: removed opinion based question

Answer

Sukhman Sandhu picture Sukhman Sandhu · Aug 3, 2017

You can add If statement for multiple stages if you want to skip multiple stages according to the branch as in:

if(env.BRANCH_NAME == 'master'){
     stage("Upload"){
        // Artifact repository upload steps here
        }
     stage("Deploy"){
        // Deploy steps here
       }
     }

or, you can add it to individual stage as in:

stage("Deploy"){
  if(env.BRANCH_NAME == 'master'){
   // Deploy steps here
  }
}