How to get pull request id from Jenkins Pipeline

Aliaksandr Kavalevich picture Aliaksandr Kavalevich · Jan 17, 2017 · Viewed 21.9k times · Source

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?

Answer

Thomas picture Thomas · Jan 20, 2017

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:

enter image description here

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}"
                }
            }
        }
    }