I'm trying to analyse my source code with Sonar using Jenkins pipelines. To ask Sonar to notify Github with the results I need to specify the Pull Request ID.
How can I get this Pull Request ID from Jenkins Pipelines?
We are using GitHub Organization Folder Plugin
to build pull requests, not GitHub pull request builder plugin
. That's why $ghprbPullId
is not working for me. Any ideas how to get the pull request id in a different way?
Multibranch Pipelines expose additional information about the branch being built through the env global variable, such as: BRANCH_NAME. Name of the branch for which this Pipeline is executing, for example master . CHANGE_ID. An identifier corresponding to some kind of change request, such as a pull request number.
A multibranch pipeline is a pipeline that has multiple branches. The main advantage of using a multibranch pipeline is to build and deploy multiple branches from a single repository. Having a multibranch pipeline also allows you to have different environments for different branches.
What's a Jenkins Multibranch Pipeline? A multibranch job is simply a folder of pipeline jobs. For every branch you have, Jenkins will create a folder. So instead of creating a pipeline job for each of the branches you have in a git repository, you could use a multibranch job.
Jenkins exposes a global variable named CHANGE_ID:
For a multibranch project corresponding to some kind of change request, this will be set to the change ID, such as a pull request number.
This variable is only populated for pull request builds, so you have to disable branch builds and enable PR builds in your pipeline's configuration for branch sources:
My pipeline step then looks like this:
def PULL_REQUEST = env.CHANGE_ID stage('Analysis') { withCredentials([[$class: 'StringBinding', credentialsId: '***', variable: 'GITHUB_ACCESS_TOKEN']]) { withSonarQubeEnv('Sonar') { withMaven(maven: 'M3') { sh "mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.2:sonar " + "-Dsonar.analysis.mode=preview " + "-Dsonar.github.pullRequest=${PULL_REQUEST} " + "-Dsonar.github.oauth=${GITHUB_ACCESS_TOKEN}" } } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With