Jenkins 多分支管道的分支名称变量是什么?

我需要知道在我的 Jenkins 多分支管道中构建了哪个分支,以便它正确地运行步骤。

我们使用了带有 devreleasemaster分支的 gitflow 模式,这些分支都用于创建工件。dev分支自动部署,其他两个不用。也有 featurebugfixhotfix的分支。应该构建这些分支,但是不应该生成工件。它们应该只是用来通知开发人员他们的代码是否有问题。

在标准构建中,我可以访问 $GIT_BRANCH变量,以了解正在构建哪个分支,但是在我的多分支管道中没有设置该变量。我也尝试了 env.GIT_BRANCH,并尝试将 $GIT_BRANCH作为参数传递给构建。好像都没用。我假设,由于构建知道正在构建的分支(我可以在控制台输出的顶部看到分支名称) ,因此我可以使用某些东西——只是找不到任何对它的引用。

125570 次浏览

There is not a dedicated variable for this purpose yet (JENKINS-30252). In the meantime you can take advantage of the fact that the subproject name is taken from the branch name, and use

env.JOB_NAME.replaceFirst('.+/', '')

This has now been resolved, see Krzysztof Krasoń's answer.

I found this stackoverflow post example useful: Git Variables in Jenkins Workflow plugin

sh '//...
git rev-parse --abbrev-ref HEAD > GIT_BRANCH'
git_branch = readFile('GIT_BRANCH').trim()
echo git_branch
//...
'

The env.BRANCH_NAME variable contains the branch name.

As of Pipeline Groovy Plugin 2.18, you can also just use BRANCH_NAME (env isn't required but still accepted.)

Another way is using the git command to obtain the branch name on the current jenkins pipeline. For example, you can add the following snippet to print the branch name in your Jenkinsfile.

...
script {
def BRANCH = sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()
echo ${BRANCH}
}
...

Jenkins documentation has a list of all the env variable for your perusal here

There are 2 branches to consider in a Jenkins multibranch pipeline job:

  1. The Jenkins job branch - env.BRANCH_NAME. This may have the same name as a git branch, but might also be called PR-123 or similar
  2. The git branch - env.GIT_BRANCH. This is the actual branch name in git.

So a job might have BRANCH_NAME=PR-123 and GIT_BRANCH=my-scm-branch-name