6

I am using Jenkins multi branch pipeline with bitbucket and I see an issue where the automatic build created for a PR fails as I rely on env.BRANCH_NAME. Problem is that this env now holds not the feature branch name as expected, instead it holds the PR is (e.g. PR-2 instead of feature/test-branch).

I have code in my job that pushes to branch based on the BRANCH_NAME. This code obviously now fails as there is no branch named PR-2.

Anyone saw this before and has a workaround?

YaOg
  • 1,748
  • 5
  • 24
  • 43
  • 1
    `CHANGE_BRANCH` should contain the source looking at [the source](https://github.com/jenkinsci/branch-api-plugin/blob/e4399aa99bc8dac1fae47915f995c2f93e7e955e/src/main/java/jenkins/branch/BranchNameContributor.java#L69) but you might be affected by [JENKINS-47617](https://issues.jenkins-ci.org/browse/JENKINS-47617). – mkobit Feb 19 '18 at 18:45
  • This Jenkins issue is exactly what hit me. env.CHANGE_BRANCH == env.BRANCH_NAME – YaOg Feb 20 '18 at 07:04
  • @mkobit Thank you very much for this hint. Everything worked as expected once we used this variable instead of `BRANCH_NAME`. If that was documented, it would have saved us a LOT of time... Actually my biggest problem with Jenkins is the poor documentation... – Marwan Tanager Mar 31 '18 at 04:11
  • This might be helpful: https://stackoverflow.com/a/66216186/5175709 – mfaani Feb 15 '21 at 22:27

1 Answers1

6

I have a stage in my pipeline setting the build name accordingly in case I have to use the CHANGE_BRANCH instead of the normal branch name.

stage('Set Build Name') {
  steps {
    script {
      if (env.BRANCH_NAME.startsWith('PR')) {
        currentBuild.displayName = "#${env.BUILD_NUMBER} - ${env.CHANGE_BRANCH}"
      } else {
        currentBuild.displayName = "#${env.BUILD_NUMBER} - ${env.BRANCH_NAME}"
      }
    }
  }
}
Christian.D
  • 879
  • 1
  • 9
  • 21
  • That would work only if you take the release that hs the fix for https://issues.jenkins-ci.org/browse/JENKINS-47617 – YaOg Nov 14 '18 at 06:02