How to check if Jenkins Pipeline runs from a pull request?

Jenkins Multibranch Pipeline reacts to changes pushed to git branches.
Sometimes we want to determine if a specific run was executed for a pull request.
Here’s how to do it.

Run stage for any pull request

In this example, we want to run the Test stage from pull requests only.

1
2
3
4
5
6
7
8
9
10
11
12
13
pipeline {
agent any
stages {
stage("Test") {
when {
changeRequest()
}
steps {
// ...
}
}
}
}

Run stage for a pull request to a specific branch

In this example, we want to run the Test stage only when the pull request is created with the develop branch as its target.

1
2
3
4
5
6
7
8
9
10
11
12
13
pipeline {
agent any
stages {
stage("Test") {
when {
changeRequest target: "develop"
}
steps {
// ...
}
}
}
}

Run stage for a pull request created from a specific branch

In this example, we want to run the Test stage only when the pull request is created from the test branch.

1
2
3
4
5
6
7
8
9
10
11
12
13
pipeline {
agent any
stages {
stage("Test") {
when {
changeRequest branch: "develop"
}
steps {
// ...
}
}
}
}

Run stage for a pull request created by specific user

In the final example, we want to run the Test stage only if the pull request was created by [email protected] user.

1
2
3
4
5
6
7
8
9
10
11
12
13
pipeline {
agent any
stages {
stage("Test") {
when {
changeRequest authorEmail: "[email protected]"
}
steps {
// ...
}
}
}
}
Share