Alex Yurkowski
Alex Yurkowski

Reputation: 1794

Get git branch name in Jenkins Pipeline/Jenkinsfile

I've create a jenkins pipeline and it is pulling the pipeline script from scm.
I set the branch specifier to 'all', so it builds on any change to any branch.

How do I access the branch name causing this build from the Jenkinsfile?

Everything I have tried echos out null except

sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()

which is always master.

Upvotes: 94

Views: 269968

Answers (14)

Davor Hrg
Davor Hrg

Reputation: 319

for me this worked in multibranch pipeline, for both regular branches and PR branches.

  environment {
     BRANCH_NAME = "${env.CHANGE_BRANCH ? env.CHANGE_BRANCH : env.BRANCH_NAME}"
  }

Upvotes: 0

Manuel Lazo
Manuel Lazo

Reputation: 862

Based on the necessity when you are working with just Jenkins Pipelines, I created the following function in a Shared Library:

package org.helpers

class Helpers {
    static def getBranchName(String branchName){
        return branchName.split('/').size() == 1 ? branchName.split('/')[-1] : branchName.split('/')[1..-1].join('/')
    }
}

From the pipeline I accessed that static method (my shared library was registered with the name pipelines):

@Library("pipelines") _
def helper = org.helpers.Helpers
pipeline {
        agent any
        environment {
            branchName = helper.getBranchName("${env.GIT_BRANCH}")
        }
       stages {
         stage('test'){
           agent any
           steps {
             script { sh "echo 'branchName: ${branchName}'" }
           }
         }
       }
}

Upvotes: 0

CyrexLt
CyrexLt

Reputation: 93

This is for simple Pipeline type - not multibranch. Using Jenkins 2.150.1

environment {
    FULL_PATH_BRANCH = "${sh(script:'git name-rev --name-only HEAD', returnStdout: true)}"
    GIT_BRANCH = FULL_PATH_BRANCH.substring(FULL_PATH_BRANCH.lastIndexOf('/') + 1, FULL_PATH_BRANCH.length())
  }

then use it env.GIT_BRANCH

Upvotes: 7

Alexey Antonenko
Alexey Antonenko

Reputation: 2627

I might want to use env.CHANGE_BRANCH to get real branch name instead of jenkins job / PR name.

Upvotes: 1

George L. Yermulnik
George L. Yermulnik

Reputation: 126

This is what worked for me for non-multi-branch pipeline with either setting SCM Branch Specifier (blank for 'any') to */branch_name or setting it to just branch_name:

BRANCH_NAME = "${GIT_BRANCH.split('/').size() > 1 ? GIT_BRANCH.split('/')[1..-1].join('/') : GIT_BRANCH}"

Upvotes: 1

Jay Reddy
Jay Reddy

Reputation: 700

To get git branch name in Jenkins, If it is a multibranch pipeline then we can easily use the env.GIT_BRANCH. But if it is a normal pipeline then we can use the SCM plugin object to retrieve the branch name.

The below code works for both normal as well as multibranch pipelines.

def branch_nem = scm.branches[0].name
if (branch_nem.contains("*/")) {
    branch_nem = branch_nem.split("\\*/")[1]
    }
echo branch_nem

Upvotes: 7

James
James

Reputation: 1293

Use multibranch pipeline job type, not the plain pipeline job type. The multibranch pipeline jobs do posess the environment variable env.BRANCH_NAME which describes the branch.

In my script..

stage('Build') {
    node {
        echo 'Pulling...' + env.BRANCH_NAME
        checkout scm
        
    }
}

Yields...

Pulling...master

Upvotes: 93

hwjp
hwjp

Reputation: 16071

FWIW the only thing that worked for me in PR builds was ${CHANGE_BRANCH}

(may not work on master, haven't seen that yet)

Upvotes: 4

Hung
Hung

Reputation: 519

For pipeline:

pipeline {
  environment {
     BRANCH_NAME = "${GIT_BRANCH.split("/")[1]}"
  }
}

Upvotes: 23

alex
alex

Reputation: 189

For me this worked: (using Jenkins 2.150, using simple Pipeline type - not multibranch, my branch specifier: '**')

echo 'Pulling... ' + env.GIT_BRANCH

Output:

Pulling... origin/myBranch

where myBranch is the name of the feature branch

Upvotes: 13

0neel
0neel

Reputation: 391

Just getting the name from scm.branches is not enough if you've used a build parameter as a branch specifier, e.g. ${BRANCH}. You need to expand that string into a real name:

scm.branches.first().getExpandedName(env.getEnvironment())

Note that getEnvironment() must be an explicit getter otherwise env will look up for an environment variable called environment.

Don't forget that you need to approve those methods to make them accessible from the sandbox.

Upvotes: 5

Attila123
Attila123

Reputation: 1042

A colleague told me to use scm.branches[0].name and it worked. I wrapped it to a function in my Jenkinsfile:

def getGitBranchName() {
    return scm.branches[0].name
}

Upvotes: 43

VonC
VonC

Reputation: 1324278

If you have a jenkinsfile for your pipeline, check if you see at execution time your branch name in your environment variables.

You can print them with:

pipeline {
    agent any

    environment {
        DISABLE_AUTH = 'true'
        DB_ENGINE    = 'sqlite'
    }

    stages {
        stage('Build') {
            steps {
                sh 'printenv'
            }
        }
    }
}

However, PR 91 shows that the branch name is only set in certain pipeline configurations:

Upvotes: 43

Alex Yurkowski
Alex Yurkowski

Reputation: 1794

Switching to a multibranch pipeline allowed me to access the branch name. A regular pipeline was not advised.

Upvotes: 5

Related Questions