Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins pipeline determine if a branch is for Bitbucket pull request

I'm using Jenkins together with the Bitbucket branch source plugin.

Everything works great, but I want to be able to run/exclude certain stages in my pipeline depending on whether the branch is associated with a pull request or not, such as:

pipeline {
  stages {
    stage('build') {
      //compile
    }    
    stage('package') {
      when {
        environment name: 'IS_PULL_REQUEST', value: 'true'
      }      
      //create deployable package
    }
  }
}

Jenkins knows when the branch is for a PR because it merges the source with the target and also displays the branch in the pull request folder on the multibranch pipeline page.

Is there an environment variable I can use within the pipeline to exclude/include stages?

like image 290
David Masters Avatar asked Mar 16 '20 18:03

David Masters


People also ask

How do I select a branch in Jenkins pipeline?

Head over to your Jenkins instance and create a new item. Enter a name for the job, and select the “Multibranch Pipeline” option at the end of the screen. Then, click on the OK button. In the next screen, go to the “Branch sources” tab, click on the “Add source” button, and choose “Git” from the dropdown menu.

How do you trigger a Jenkins pipeline on a pull request?

For Jenkins to receive PR events through the pull request plugin, you need to add the Jenkins pull request builder payload URL in the Github repository settings. If you need just the PR triggers, you can select the “Let me select individual events” option and select just the “Pull requests” option.

What is difference between pipeline and Multibranch pipeline?

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.


1 Answers

You can use BRANCH_NAME and CHANGE_ID environment variables to detect pull requests. When you run a multibranch pipeline build from a branch (before creating a pull request), the following environment variables are set:

  • env.BRANCH_NAME is set to the repository branch name (e.g. develop),
  • env.CHANGE_BRANCH is null,
  • env.CHANGE_ID is null.

But once you create a pull request, then:

  • env.BRANCH_NAME is set to the PR-\d+ name (e.g. PR-11),
  • env.CHANGE_BRANCH is set to the real branch name (e.g. develop),
  • env.CHANGE_ID is set to the pull request ID (e.g. 11).

I use the following when condition in my pipelines to detect pull requests:

when {
    expression {
        // True for pull requests, false otherwise.
        env.CHANGE_ID && env.BRANCH_NAME.startsWith("PR-")
    }
}
like image 64
Szymon Stepniak Avatar answered Sep 27 '22 22:09

Szymon Stepniak