Jenkins pipeline determine if a branch is for Bitbucket pull request

一世执手 提交于 2020-03-20 05:56:17

问题


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?


回答1:


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



回答2:


In Declarative Pipelines, you can also use the built-in condition changeRequest inside the when directive to determine if the branch is associated with a pull request.

stage('package') {
  when {
    changeRequest()
  }      
  //create deployable package
}

You can also check if the pull request is targeted at a particular branch:

stage('package') {
  when {
    changeRequest target: 'master'
  }      
  //create deployable package
}

See https://jenkins.io/doc/book/pipeline/syntax/#when.



来源:https://stackoverflow.com/questions/60711551/jenkins-pipeline-determine-if-a-branch-is-for-bitbucket-pull-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!