Search code examples
jenkinsmultibranch-pipelinejenkins-blueocean

Jenkins Multibranch Pipeline: How to checkout only once?


I have created very basic Multibranch Pipeline on my local Jenkins via BlueOcean UI. From default config I removed almost all behaviors except one for discovering branches. The config looks line follows:

config

Within Jenkinsfile I'm trying to setup following scenario:

  • Checkout branch
  • (optionally) Merge it to master branch
  • Build Back-end
  • Build Front-end

Snippet from my Jenkinsfile:

pipeline {
  agent none   
  stages {    
    stage('Setup') {
      agent {
        label "master"
      }    
      steps {
        sh "git checkout -f ${env.BRANCH_NAME}"
      }
    }

    stage('Merge with master') {
      when {
        not {
          branch 'master'
        }
      }    
      agent {
        label "master"
      }    
      steps {
        sh 'git checkout -f origin/master'
        sh "git merge --ff-only ${env.BRANCH_NAME}"
      }
    }

    stage('Build Back-end') {
      agent {
        docker {
          image 'openjdk:8'
        }
      }

      steps {
          sh './gradlew build'              
      }
    }

    stage ('Build Front-end') {
      agent {
        docker {
          image 'saddeveloper/node-chromium'
        }
      }

      steps {
        dir ('./front-end') {
          sh 'npm install'              
          sh 'npm run buildProd'
          sh 'npm run testHeadless'
        }
      }
    }
  }
}

Pipeline itself and building steps works fine, but the problem is that Jenkins adds "Check out from version control" step before each stage. The step looks for new branches, fetches refs, but also checks out current branch. Here is relevant output from full build log:

// stage Setup
 > git checkout -f f067047bbdd3a5d5f9d1f2efae274bc175829595
sh git checkout -f my-branch
// stage Merge with master
 > git checkout -f f067047bbdd3a5d5f9d1f2efae274bc175829595
sh git checkout -f origin/master
sh git merge --ff-only my-branch
// stage Build Back-end
 > git checkout -f f067047bbdd3a5d5f9d1f2efae274bc175829595
sh ./gradlew build
// stage Build Front-end
 > git checkout -f f067047bbdd3a5d5f9d1f2efae274bc175829595
sh npm install
sh npm run buildProd
sh npm run testHeadless

So as you see it effectively resets working directory to particular commit before every stage git checkout -f f067...595.

Is there any way to disable this default checkout behavior? Or any viable option how to implement such optional merging to master branch?

Thanks!


Solution

  • By default, git scm will be executed in a Jenkins pipeline. You can disable it by doing:

    pipeline {
        agent none
        options {
            skipDefaultCheckout true
        }
        ...
    

    Also, I'd recommend take a look to other useful pipeline options https://jenkins.io/doc/book/pipeline/syntax/#options