Ivan Stoyanov Ivan Stoyanov - 1 year ago 112
Java Question

Pull the current branch with Jenkins workflow multibranch plugin

I have set up Jenkins and I am using the Jenkins workflow multibranch plugin. I have configured it to listen for commits in a GitHub repo for any branch.

This is a sample of the

committed in one of the branches:

node {
// Mark the code checkout 'stage'....
stage 'Checkout'

// Get some code from a GitHub repository
git url: 'git@github.com:Me/my-repo.git', credentialsId: '###'

// Get the maven tool.
// ** NOTE: This 'M3' maven tool must be configured
// ** in the global configuration.
def mvnHome = tool 'M3'

stage 'Build'
sh "${mvnHome}/bin/mvn clean install"

When I commit something in this branch a build is triggered. The problem is that git checkouts the master branch and not the branch that is building at the moment.

How can I checkout the branch for the current build?

The solutions so far

  1. Use
    checkout scm
    instead of
    git url: 'git@github.com:Me/my-repo.git', credentialsId: '###'
    This way you will checkout the current branch.

  2. Use the branch variable - check this for more info: Jenkins Multibranch workflow: What is the branch name variable?


In your Jenkinsfile, add the name of the branch to checkout with the branch parameter on the git line:

git {...}, branch: 'branch-name'

Some build triggers set an environment variable that contains the branch name (e.g., Gerrit Trigger Plugin sets GERRIT_BRANCH), which would allow you to set branch to that environment variable instead of hard-coding per branch.