问题
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
.
回答1:
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:
- Branch Conditional (see this groovy script)
- parallel branches pipeline (as seen by the OP)
回答2:
Use multibranch pipeline.. not pipeline
In my script..
stage('Build') {
node {
echo 'Pulling...' + env.BRANCH_NAME
checkout scm
}
}
Yields...
Pulling...master
回答3:
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
}
回答4:
Switching to a multibranch pipeline allowed me to access the branch name. A regular pipeline was not advised.
回答5:
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
回答6:
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.
来源:https://stackoverflow.com/questions/42383273/get-git-branch-name-in-jenkins-pipeline-jenkinsfile