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
.
This question is related to
git
jenkins
branch
jenkins-pipeline
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
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
}
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
For pipeline:
pipeline {
environment {
BRANCH_NAME = "${GIT_BRANCH.split("/")[1]}"
}
}
Switching to a multibranch pipeline allowed me to access the branch name. A regular pipeline was not advised.
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.
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
FWIW the only thing that worked for me in PR builds was ${CHANGE_BRANCH}
(may not work on master
, haven't seen that yet)
Source: Stackoverflow.com