问题
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
isnull
,env.CHANGE_ID
isnull
.
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