You can filter by name your branches in a multibranch job setting.
Including certain branches is trickier, since Jenkins does not have this settings in classic jobs.
But using a Jenkinsfile, you can try for testing:
node {
stage('Check Branch') {
script {
// Check if branch is filed as a PR
if (env.CHANGE_ID) {
echo "This branch is filed as a PR."
// Check if branch is MASTER or another special branch
if (env.BRANCH_NAME == 'MASTER' || env.BRANCH_NAME == 'special-branch') {
echo "This is a special branch. Running build."
// Your build steps here
} else {
echo "This is not a special branch. Skipping build."
}
} else {
echo "This branch is not filed as a PR. Running build."
// Your build steps here
}
}
}
}
This will still trigger job, though. And if Jenkins is configured to report about builds to git server - it will report, even if nothing actually happened.
True, a more advanced approach would be to intercept or decide on the job execution at a higher level, outside the Jenkinsfile's logic.
But that does not seem supported.
Even if the job is triggered, you can do something to avoid reporting when nothing happened, though.
node {
stage('Check Branch') {
script {
// Assuming you do not want to proceed with anything if it is a PR on a non-special branch
if (env.CHANGE_ID && env.BRANCH_NAME != 'MASTER' && env.BRANCH_NAME != 'special-branch') {
echo "That is a PR on a non-special branch. Exiting early without notifying."
currentBuild.result = 'ABORTED'
error("Exiting early due to branch conditions.")
}
}
}
// If the above condition is not met, your other stages and steps will execute as normal.
stage('Build') {
// Your build steps here
}
stage('Notify') {
// Your SCM notification step here, e.g., githubNotify
// That will only run if the previous stages completed without erroring out.
}
}
The early error
will stop the pipeline and will not proceed to the subsequent stages.
Setting the currentBuild.result = 'ABORTED'
will mark the build as aborted, which you can interpret as a conditional skip.
And the 'Notify' stage, which contains the step that communicates back to the SCM, is only executed if the pipeline did not encounter an error in the preceding stages.
However:
- The job will still appear in Jenkins, and it will show as either '
ABORTED
' or 'FAILURE
' (depending on if you set the currentBuild.result
or not).
- you would still have an overhead where jobs are triggered and resources are consumed (even if momentarily) only to decide they should not run. That can become an issue if you have a high frequency of branch/PR creation.