How to Build on Pull Request in Jenkins: Step-by-Step Guide
To build on a pull request in Jenkins, use a
Multibranch Pipeline job or configure the GitHub Pull Request Builder plugin. These setups detect pull requests automatically and trigger builds when a PR is created or updated.Syntax
Use a Jenkinsfile with a Multibranch Pipeline or configure the GitHub Pull Request Builder plugin with these key parts:
- Multibranch Pipeline: Jenkins scans branches and PRs automatically.
- Jenkinsfile: Defines build steps, often with
checkout scmto get PR code. - Triggers: Set to build on PR events like open, update, or comment.
groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
checkout scm
sh 'echo Building pull request'
}
}
}
triggers {
pollSCM('H/5 * * * *')
}
}Example
This example shows a Jenkinsfile for a Multibranch Pipeline that builds pull requests automatically. It checks out the PR code and runs a simple build step.
groovy
pipeline {
agent any
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Build') {
steps {
sh 'echo Building pull request branch'
}
}
}
triggers {
pollSCM('H/5 * * * *')
}
}Output
Building pull request branch
Common Pitfalls
- Not using a Multibranch Pipeline job causes Jenkins to miss PR events.
- Forgetting to add a Jenkinsfile in the repo means no build steps run.
- Incorrect SCM polling or webhook setup can prevent builds from triggering.
- Using freestyle jobs without PR plugins usually requires manual triggers.
groovy
/* Wrong: Freestyle job without PR trigger */ // No automatic build on PR /* Right: Multibranch Pipeline with Jenkinsfile */ pipeline { agent any stages { stage('Build') { steps { checkout scm sh 'echo Building PR' } } } }
Quick Reference
Tips for building on pull requests in Jenkins:
- Use Multibranch Pipeline jobs for automatic PR detection.
- Place a
Jenkinsfilein your repo root to define build steps. - Configure webhooks in GitHub/GitLab to notify Jenkins on PR events.
- Use plugins like
GitHub Pull Request Builderfor freestyle jobs if needed. - Test your setup by opening or updating a pull request and checking Jenkins build status.
Key Takeaways
Use Jenkins Multibranch Pipeline jobs to automatically build pull requests.
Always include a Jenkinsfile in your repository to define build steps.
Set up webhooks in your Git hosting service to trigger Jenkins builds on PR events.
Avoid freestyle jobs for PR builds unless using specific PR builder plugins.
Test your configuration by creating or updating a pull request and verifying Jenkins triggers a build.