Multibranch pipelines and pull requests

Jenkins · Practical · 10 min

Teams work on many branches at once; multibranch jobs give each one CI without manual job setup.

A Multibranch Pipeline job points at a repository instead of a branch. Jenkins scans it, creates a child job for every branch (and, with a branch source plugin like GitHub Branch Source, every pull request) that contains a Jenkinsfile, and deletes child jobs when branches disappear. An Organization Folder goes one level higher and discovers whole repositories.

Each branch job builds its own branch's Jenkinsfile. Useful variables:

  • BRANCH_NAME: the branch, or PR-42 for pull requests.
  • CHANGE_ID, CHANGE_TARGET, CHANGE_AUTHOR: set for pull requests only.

when { branch 'main' } and when { changeRequest() } let one Jenkinsfile behave differently for main, feature branches and PRs: test everywhere, deploy only from main.

With the GitHub or GitLab branch source plugins, webhooks trigger scans and builds immediately, and build status is reported back to the commit and the pull request as a check.

Pull requests from forks are a security concern: a fork could change the Jenkinsfile to print secrets. Branch sources therefore offer trust settings; by default the Jenkinsfile is taken from the target branch for untrusted forks, not from the PR.

Example

// One Jenkinsfile, different behaviour per branch type
pipeline {
    agent any
    stages {
        stage('Test') {
            steps { sh 'make test' }
        }
        stage('PR info') {
            when { changeRequest() }
            steps { echo "PR ${env.CHANGE_ID} into ${env.CHANGE_TARGET}" }
            // PR 42 into main
        }
        stage('Deploy') {
            when { branch 'main' }
            steps { sh './deploy.sh' }
        }
    }
}

Remember

  • Multibranch jobs create one child job per branch or PR with a Jenkinsfile
  • BRANCH_NAME and CHANGE_* describe the branch or PR
  • Fork PRs are untrusted: their Jenkinsfile changes are not used by default

Watch out for

  • Creating one pipeline job per branch by hand.

Check yourself

  1. In a multibranch job, what is env.BRANCH_NAME for pull request #42?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.jenkins.io/doc/book/pipeline/multibranch/