How to check if a pipeline is triggered from a pull request

38.9k Views Asked by At

I'm using Jenkins pipeline to build Pull Requests branches using the GitHub Organization plugin.

I can build them fine, but I want to avoid some steps (such as publishing the artifacts). Checking git's current branch gives me the PR's target since the PR branch is being merged into the target before the build is attempted.

How can I check if the build is being initiated from a PR vs than a regular branch build?

4

There are 4 best solutions below

5
On BEST ANSWER

At least on Jenkins 2.16 env.BRANCH_NAME gives the source branch not the target branch. You could do something like:

if (env.BRANCH_NAME == "master") {
  sh "./publish.sh"
}

Other env vars that could be useful are the CHANGE_* variables. E.g.,

CHANGE_AUTHOR='me'
CHANGE_ID='6'
CHANGE_TARGET='master'
CHANGE_TITLE='Update README.md'
CHANGE_URL='https://github.com/test-org/test-repo/pull/6'

For documentation on these and more: https://ci.eclipse.org/webtools/env-vars.html/

0
On

For anyone looking to solve this scenario, you can SIMPLY turn off your "Pull requests" event in the Webhooks section in your Github organization.

Steps:

  1. Go to your repository settings in GitHub.
  2. Click on Webhooks.
  3. Select the webhook used for Jenkins integration.
  4. Under "Which events would you like to trigger this webhook?", select "Let me select individual events."
  5. Choose only the events you are interested in, such as "Pushes," and avoid selecting "Pull requests."
  6. Save your changes.
0
On

To specifically detect GitHub pull requests, this can be used:

  script {
    if (env.BRANCH_NAME == 'master') {
      sh 'make'
    } else if (env.BRANCH_NAME.startsWith('PR')) {
      // do actions for pull request
    } else {
      // some other branch
    } 
  }

Of course, if you expect to have branches starting with PR on your main repository this wouldn't be reliable. The nice thing about it is that script can be used also in post not just stages, which is useful since when is not allowed in post. If you don't care about that it's worth looking into the when directive. There is some documentation from Cloudbees and Jenkins with some examples.

1
On

The env variable CHANGE_ID only exists when the build is triggered from a Pull Request check.

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, if supported; else unset.