Jenkins Multibranch - exclude branches that are also PRs *except*

563 views Asked by At

When setting up a Jenkins multibranch pipeline, I would like to "Exclude branches that are filed as PRs", EXCEPT for certain branches, which I want to build both the PR and the original branch simultaneously.

Example using MASTER:

  • Open a PR for STORY-999
    • PR gets built
    • STORY-999 doesn't
  • Open a PR for MASTER
    • PR gets built
    • MASTER also gets built
1

There are 1 answers

5
VonC On BEST ANSWER

Since, as noted in the comments by David Navrkal, the env.CHANGE_ID variable is indeed only set for PR builds and not branch builds, you will need to check if there is an open PR for the current branch:

pipeline {
    agent any

    // List of branches that should always be built
    def alwaysBuildBranches = ['MASTER', 'DEVELOP', 'HOTFIX']

    stages {
        stage('Pre-Build Checks') {
            steps {
                script {
                    // Check if it is a branch build and not in the alwaysBuildBranches list
                    if (env.CHANGE_ID == null && !alwaysBuildBranches.contains(env.BRANCH_NAME)) {
                        // Add logic to check if there is an open PR for the current branch
                        // If there is an open PR, set a flag or variable to indicate this
                        boolean hasOpenPR = false // Placeholder for the actual check
                        
                        // Skip the build if there is an open PR for this branch
                        if (hasOpenPR) {
                            currentBuild.result = 'ABORTED'
                            error('Aborting build for branch ' + env.BRANCH_NAME + ' since there is an open PR')
                        }
                    }
                }
            }
        }
        stage('Build') {
            steps {
                echo 'Building...'
                // Your build commands go here
            }
        }
    }
}

alwaysBuildBranches is a list containing the names of branches that should always be built.
The pre-build check now verifies if the current branch is not in the alwaysBuildBranches list and if there is no CHANGE_ID (indicating it is not a PR build). If the current branch is not one of the special branches and there is an open PR for it, the build is aborted.

That approach allows you to dynamically include any number of branches that should bypass the PR check and be built every time.
But the logic to check if there is an open PR (boolean hasOpenPR = false) needs to be implemented based on your specific repository setup and might involve querying your repository's API or using some plugin that provides this information.