The orders-api Jenkinsfile is the result of six modules of growth: each lesson added a stage that solved something specific. It works, but nobody has sat down to decide what should run on a pull request, on main and on a tag, how long it should take or in what order things should fail. In the previous lesson you called it the "commit stage" of the deployment pipeline: the first one, the most frequent one and the one that gives the feedback the team expects within minutes. In this lesson you will design it with intent: you will settle the table of what runs on each type of build, measure durations per stage, reorder by cost and likelihood of failure, treat concurrent PR and main builds differently, add milestone, review compiled output and caches, improve the traceability of the artifact and get the triggering of the CD pipeline from tags ready. At the end you will have the resulting complete Jenkinsfile.

What Is Expected of the Commit Stage

The commit stage has three responsibilities, and it is best not to ask more of it:

Responsibility What it involves in orders-api
Reject what is broken, fast Build, unit and integration tests, smoke: if something fails, the author knows within minutes
Produce the candidate artifact A versioned, traceable and reproducible jar that, if everything passes, is published to Nexus
Give a reliable signal Green means "can be integrated"; red, "broken"; yellow, "degraded" (the semantics from 06-03)

What is not its responsibility: deploying to staging or production, waiting for approvals or running long tests against an environment. That is the job of the CD pipeline in 07-03. Mixing it into the same Jenkinsfile would make every main build longer and fill the file with conditions.

What Runs on PRs, on main and on Tags

The orders-api multibranch job builds three kinds of heads: PRs (PR-42), the main branch and vX.Y.Z tags (discovered since 06-01). This is TecnoShop's design table:

Stage PR main Tag vX.Y.Z Why
PR info ✓ Context in the PR console
Build ✓ ✓ ✓ The basis for everything
Checks (unit tests + dependency tree) ✓ ✓ ✓ The essential feedback; on the tag, it guarantees that what gets published was tested on that commit
Integration tests ✓ ✓ ✓ Same as unit tests: cheap and very informative
Package ✓ ✓ ✓ The PR must prove that it can be packaged; the PR artifact never leaves Jenkins
Smoke ✓ ✓ ✓ A jar that does not start is a broken PR
Quality analysis + Quality Gate ✓ SonarQube Community Build only analyzes the main branch (06-04); the tag's commit has already been through main
Publish ✓ (SNAPSHOT) ✓ (release) Only integrated code is published; PRs never publish
Deploy to dev ✓ Continuous deployment to dev
Trigger CD ✓ Every published release starts its promotion (07-03)

Three decisions deserve a comment:

  • PRs run all the tests. The temptation to cut tests on PRs "to go faster" moves the failure to main, which is where it costs the most. If the PR is slow, you speed up the stage; you do not remove it.
  • The tag tests again. It might seem redundant, but the version commit (the one that changes pom.xml to 1.1.0) was never built as main, and the tag is the only build that produces the release artifact. Building once means this build, not "some similar earlier build".
  • main and the tag publish different things: a SNAPSHOT for integration between teams and for dev, an immutable release for staging and production.

The Feedback Target and How to Measure It

TecnoShop sets an explicit target: a PR gets its result in under 10 minutes, counted from the push until the Jenkins check in GitHub. For main, which does more, the target is 15 minutes to dev.

A target without measurement is just a wish. Jenkins offers three ways to see where the time goes:

  • Pipeline Graph View (the plugin from 02-06): for each build, the duration of each stage and each parallel branch. Ideal for analyzing a specific build.
  • Stage View (on the job page): a grid of the latest builds with the duration of each stage and, in the header, the average per stage (Average stage times). Ideal for spotting trends.
  • The Stage View plugin API, wfapi/describe, to extract the data:
# JENKINS_URL, JENKINS_USER_ID and JENKINS_API_TOKEN variables from 03-06 (fake values)
curl -s -u "$JENKINS_USER_ID:$JENKINS_API_TOKEN" \
  "$JENKINS_URL/job/orders-api/job/main/lastSuccessfulBuild/wfapi/describe" \
  | jq -r '"queue: \(.queueDurationMillis / 1000 | floor) s",
           (.stages[] | "\(.name): \(.durationMillis / 1000 | floor) s")'
  • job/orders-api/job/main/: inside the multibranch job, each branch is a job; a PR would be job/PR-42/.
  • lastSuccessfulBuild/wfapi/describe: the summary of the last green build: stages, status and durations.
  • queueDurationMillis: the time the build waited in the queue for an executor. It counts toward feedback, even though it is not the pipeline's fault: if it grows, you are short of executors (a topic for 08-01 and 08-05).
  • .stages[]: one line per stage with its duration in seconds.

With several weeks of builds, the duration metrics exported by the Prometheus plugin (05-05) let you chart the trend in Grafana and alert if an average PR goes over 10 minutes.

Typical orders-api durations in the lab (approximate; yours will vary):

Stage PR main
Queue + checkout + reading APP_VERSION 0:30 0:30
Build 0:40 0:40
Checks (in parallel) 1:30 1:30
Integration tests 1:00 1:00
Package 0:25 0:25
Smoke 0:35 0:35
Quality analysis + Quality Gate - 2:00
Publish - 0:30
Deploy to dev - 0:45
Total ≈ 4:40 ≈ 7:55

Today both targets are met comfortably. The value of measuring is spotting when that stops being true: when the number of tests multiplies or the security scans from 07-05 arrive, this table will tell you which stage to parallelize or move.

Ordering Stages by Cost and Likelihood of Failure

The rule from 04-07 ("fail fast") has a more precise formulation: cheap stages with a high likelihood of failure go first; expensive ones with a low likelihood go last.

Stage Cost Likelihood of failure Position
Build Low High (syntax errors, types) First
Checks Low-medium High (most logic failures) Second, in parallel
Integration tests Medium Medium Third
Package Low Low Fourth
Smoke Low Low-medium (configuration, startup) Fifth
Quality analysis + Quality Gate High (analysis + waiting for the server) Low-medium After Smoke
Publish, Deploy to dev, Trigger CD Medium Low At the end: they have effects outside Jenkins

The only change from module 6: Package and Smoke move ahead of Quality analysis. Before, a jar that would not start was discovered after waiting two minutes for SonarQube; now, in 35 seconds. The analysis still has what it needs (compiled classes and the JaCoCo report in target/) because nobody runs clean in between.

Concurrent Builds: PRs vs. main

Until now, disableConcurrentBuilds() treated all heads the same: if Diego pushes twice in a row to his PR, the second build waits for the first one to finish, even though the first one is now useless. The abortPrevious parameter changes that behavior:

Option What happens to a new build if another one is running
disableConcurrentBuilds() It waits in the queue until the previous one finishes
disableConcurrentBuilds(abortPrevious: true) It aborts the previous one and starts right away

What suits each type of build?

  • PR: the previous build is obsolete as soon as a new push arrives; aborting it saves executors and speeds up feedback. abortPrevious: true.
  • main: every merged commit must be verified, publish its SNAPSHOT and be deployed to dev. Aborting a build halfway through Publish or Deploy to dev could leave the server half-updated. abortPrevious: false: builds wait their turn.
  • Tags: each tag is its own job and is built once; the value does not matter much, but aborting a release publication halfway makes no sense: false.

In a single line:

        disableConcurrentBuilds(abortPrevious: env.CHANGE_ID != null)
  • env.CHANGE_ID: the PR number, which only exists in PR builds (04-05). Like BRANCH_NAME in the cron of triggers, it is available from the start of the build.
  • env.CHANGE_ID != null: true on PRs, false on main and on tags.

A detail of the Jenkins queue: if three merges reach main while the first one is being built, the second and third do not produce two waiting builds but one, which includes both commits. That is acceptable: that build verifies the integrated state of both.

milestone: Never Publish or Deploy Builds That Are Out of Order

In 04-01 you met milestone: when a build passes a milestone, older builds that have not passed it yet are aborted, and an older build can never pass a milestone that a newer one has already passed.

With main running in series, two main builds never overlap, so the milestone has nothing to do... as long as nobody changes that option. If tomorrow the team decides to allow concurrent main builds to go faster (a reasonable alternative with more executors), the risk appears: the build of commit A, which is slower, could publish and deploy to dev after the build of commit B, leaving dev with old code. A milestone() at the start of Publish makes that impossible, whatever the concurrency setting:

            steps {
                milestone(label: 'Publish')
                // ... tag check and publication ...
            }
  • milestone(label: 'Publish'): without ordinal, Jenkins numbers milestones in order of appearance. The label appears in the console and in the build view.
  • It goes inside Publish, not before it, so that it only counts in the builds that are going to publish (main and tags); PRs never reach it.
main design Advantage Drawback
In series + milestone (TecnoShop) Every commit is published and deployed in order; simple A commit waits for the previous one
Concurrent + milestone Faster feedback with several merges in a row More executors; old builds are aborted when they reach Publish

One warning: milestone compares build numbers. A Replay or a Rebuild of an old main build creates a build with a new number and old code, and the milestone will let it through. That is why TecnoShop's rule is that dev is rolled back with a new commit (or a revert), never by rerunning old builds.

Reusing Compiled Output and Making the Most of Caches

A Single clean

clean appears once, in Build. After that, each stage reuses what the previous one left in target/:

Stage Command What it reuses
Build clean compile Nothing: it deliberately starts from scratch
Tests test The compiled classes: Maven sees that they are up to date and does not recompile
Integration tests failsafe:integration-test failsafe:verify It invokes only the Failsafe goals, without running through the lifecycle
Package -DskipTests package Classes and resources already generated
Publish -DskipTests -Dmaven.install.skip=true deploy The same; the jar is repackaged identically thanks to project.build.outputTimestamp (06-05)

Adding clean to another stage "just in case" would delete the JaCoCo report that SonarQube needs and force everything to be recompiled. If a stage needs to start from scratch, that is a sign that something depends on the state of the workspace in a fragile way.

The Caches

Cache Where What it saves Since
Local Maven repository /home/jenkins/agent/.m2/repository on the linux-agent-01 volume (node variable MAVEN_OPTS) Downloading dependencies and plugins on every build 05-01
Nexus proxy maven-central and npm-registry Going out to the Internet; survives Maven Central outages 06-05
npm cache npm_config_cache on the agent and npm ci --prefer-offline Package downloads in catalog-web 06-02

And what is not cached: target/ and node_modules/ between builds. A build that starts with leftovers from the previous one is no longer reproducible, and cleanWs() in cleanup guarantees that. When the agents become ephemeral (08-01, 08-02), the local Maven repository will disappear with each agent and the Nexus proxy will become the main cache.

Parameters You No Longer Need: Goodbye to ENVIRONMENT

The ENVIRONMENT parameter (dev, staging, production) arrived in 02-03 when orders-api had a single job for everything. Today the commit stage only deploys to dev, and promotion to staging and production will be the responsibility of the CD pipeline. Keeping it suggests that a main build can deploy to production by picking a value from a list, which is exactly what we do not want.

The parameter is removed and the Deploy to dev condition becomes:

            when {
                allOf {
                    branch 'main'
                    expression { params.RUN_TESTS }
                }
            }

RUN_TESTS stays, with its safe default (true): it is still useful for checking in a minute that a branch compiles, and without tests nothing is analyzed, published, deployed or sent to CD. After the first build with the new Jenkinsfile, Build with Parameters will no longer show ENVIRONMENT.

Artifact Version and Traceability

For each jar, TecnoShop can already answer where it came from: build-info.txt (the infoBuild step), fingerprints, Nexus metadata and the Git tag (06-05). What is missing is for the deployed service to know which version it is, without having to look at the server. Spring Boot solves this with the build-info goal of its Maven plugin, which generates META-INF/build-info.properties inside the jar.

In pom.xml, in the plugin that already exists:

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>build-info</goal>
                        </goals>
                        <configuration>
                            <time>off</time>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
  • <goal>build-info</goal>: it runs automatically in the generate-resources phase, so it is part of compile, package and deploy without changing any pipeline command.
  • The generated file contains build.group, build.artifact, build.name and build.version (for example, 1.1.0).
  • <time>off</time>: it does not include the build date. By default it would use project.build.outputTimestamp, which is a fixed date so that the jar is reproducible and could be mistaken for the real date; the real date is already in build-info.txt and in Jenkins. The important part: the jar is still identical byte for byte between Package and Publish.

And in src/main/resources/application.properties, to publish the info endpoint as well as health:

server.port=8081
management.endpoints.web.exposure.include=health,info
  • management.endpoints.web.exposure.include: by default Spring Boot only exposes the health endpoint over HTTP; this line adds info, which shows the information from build-info.properties. No other Actuator endpoint (such as env or heapdump, which reveal internal data) is exposed.

After the change, on any server:

curl -s http://dev-01.tecnoshop.local:8081/actuator/info
{"build":{"artifact":"orders-api","name":"orders-api","version":"1.1.0-SNAPSHOT","group":"com.tecnoshop"}}

In 07-03 the acceptance tests will use this endpoint to check that staging is running exactly the requested version, and in 07-04 you will use it to find out which version is on each server. If you also wanted to include the commit, the git-commit-id-maven-plugin plugin generates a git.properties file that Actuator shows automatically; bear in mind that by default it includes the build date and would break reproducibility unless you exclude those properties.

The build description completes traceability in Jenkins. infoBuild already sets it (orders-api 1.1.0-SNAPSHOT (main)), and the Trigger CD stage will append the promotion to it, so that the tag's build list reads orders-api 1.1.0 (v1.1.0) → orders-api-cd.

Getting Ready to Trigger the CD Pipeline

When a tag build publishes the release to Nexus, its job as the commit stage is done: the rest (staging, acceptance, approval, production) belongs to the orders-api-cd CD pipeline, which you will create in the next lesson inside an orders-delivery folder (you will see why a folder there). The commit stage only has to notify it:

        stage('Trigger CD') {
            when {
                allOf {
                    tag pattern: 'v\\d+\\.\\d+\\.\\d+', comparator: 'REGEXP'
                    expression { params.RUN_TESTS }
                }
            }
            steps {
                script {
                    def sha256 = sh(script: 'sha256sum target/orders-api-*.jar | cut -d " " -f 1',
                                    returnStdout: true, label: 'SHA-256 of the published jar').trim()
                    build job: '/orders-delivery/orders-api-cd',
                          wait: false,
                          parameters: [
                              string(name: 'VERSION', value: env.APP_VERSION),
                              string(name: 'SHA256', value: sha256)
                          ]
                    currentBuild.description = "${currentBuild.description} → orders-api-cd"
                }
            }
        }
  • when: the same tag condition as Publish, and only if the tests ran (otherwise Publish would not have run).
  • sha256sum target/orders-api-*.jar: the SHA-256 sum of the jar that this build tested and published. cut -d " " -f 1 keeps the sum, without the file name.
  • build job: '/orders-delivery/orders-api-cd': the build step from 04-01. The leading slash indicates an absolute path from the Jenkins root; without it, Jenkins would look for the job relative to the multibranch folder.
  • wait: false: it triggers CD and finishes, without waiting. The tag build ends in minutes; CD can take hours (it waits for an approval) and there is no point in keeping an agent executor busy in the meantime.
  • parameters: VERSION is the pom.xml version (1.1.0), which the Publish stage has already checked matches the tag. SHA256 will let the CD pipeline verify that the jar it downloads from Nexus is exactly the one this build tested: hard evidence of "build once".
  • currentBuild.description: records the promotion in the build list.

Until the next lesson, do not push version tags. If one were built, it would publish the release and the Trigger CD stage would fail with a message along the lines of No item named /orders-delivery/orders-api-cd found. It would not be serious (the release would be published and CD could be triggered by hand later), but the build would end up red.

One more detail: a tag build runs, like all TecnoShop builds, with the internal system identity, which can trigger any job. If the Authorize Project plugin is ever installed so that builds run with a user's identity, that user will need the Job/Build permission on orders-api-cd.

The Team Rules When main Breaks

notifyTeam raises the alarm when main starts failing (06-07). What happens next is up to the team. TecnoShop's rules, written in the README of each repository:

# Rule Why
1 Whoever merged the last change deals with it as soon as they get the notice and says so in the #ci-orders thread ("I'm on it") One person responsible, visible to everyone
2 If it is not fixed within 15 minutes, the PR is reverted (GitHub's Revert button, which creates a revert PR) and the fix is done calmly on another branch Reverting is almost always faster than fixing under pressure
3 While main is red, nobody merges anything other than the fix or the revert Merging on top of a red build hides the next failure
4 Never turn it green by disabling, deleting or skipping tests; a flaky test goes into quarantine with an issue and a deadline (06-03) A false green is worse than a red
5 If the nightly build fails (with no new changes), the first team member to arrive deals with it; it usually points to an external dependency or a date-dependent test Nobody "merged" that failure, but it still has to be dealt with
6 If main breaks more than twice in a week for the same reason, someone sets aside time to remove the cause Making sure the problem does not come back is better than fixing it quickly every time

The catalog-web CI, Revisited

The same analysis applied to catalog-web (its complete state is at the end of 06-04, with notifyTeam since 06-07):

Stage PR main Change in this lesson Reason
Tests per Node version → Test ✓ ✓ node-18 is dropped from the matrix axis Node.js 18 reached end of life in 2025; testing on unsupported versions uses up executors without adding anything
Tests per Node version → Coverage (only node-22) ✓ ✓ Saves coverage/lcov.info with stash So that the analysis does not repeat the tests
Build ✓ ✓ No changes The PR must prove that it builds
Quality analysis ✓ No longer runs npm ci or npm test: it retrieves the coverage with unstash Saves well over a minute and analyzes the coverage of the same tests that were published
Quality Gate ✓ No changes No agent, as in 06-04
options disableConcurrentBuilds(abortPrevious: env.CHANGE_ID != null) The same criterion as in orders-api

The two snippets that change:

                    stage('Coverage') {
                        when {
                            environment name: 'NODE_VERSION', value: 'node-22'
                        }
                        steps {
                            recordCoverage(/* ... same as in 06-04 ... */)
                            stash name: 'jest-coverage', includes: 'coverage/lcov.info'
                        }
                    }
        stage('Quality analysis') {
            // ... when, agent, options and environment unchanged ...
            steps {
                unstash 'jest-coverage'
                nodejs(nodeJSInstallationName: 'node-22', configId: 'npmrc-tecnoshop') {
                    withSonarQubeEnv('sonar-tecnoshop') {
                        sh '"$SCANNER_HOME/bin/sonar-scanner"'
                    }
                }
            }
        }
  • stash name: 'jest-coverage': saves only the LCOV report, a few KB, which is what sonar-project.properties points SonarQube to as the coverage report.
  • unstash 'jest-coverage': puts it in the workspace of the analysis, which has done its own checkout.
  • nodejs(...) stays because SonarQube's JavaScript analyzer needs a Node environment to run.

catalog-web does not publish or deploy yet: when it does (as a container image in module 8), it will follow the same table as orders-api.

The Complete orders-api Jenkinsfile

With this lesson's changes: no ENVIRONMENT, different concurrency for PRs, Package and Smoke before the analysis, milestone in Publish and the Trigger CD stage. The lines marked // 07-02 are new or changed.

@Library('[email protected]') _

pipeline {
    agent {
        label 'linux'
    }

    options {
        timestamps()
        timeout(time: 30, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
        disableConcurrentBuilds(abortPrevious: env.CHANGE_ID != null)      // 07-02
        preserveStashes(buildCount: 5)
    }

    parameters {
        booleanParam(name: 'RUN_TESTS', defaultValue: true,
                     description: 'Uncheck only to quickly verify that the code compiles. Without tests nothing is analyzed, published or deployed, and the CD pipeline is not triggered.')   // 07-02
    }

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

    environment {
        MAVEN_ARGS        = '-B -ntp'
        MAVEN_SETTINGS_ID = 'maven-settings-tecnoshop'
        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} | RUN_TESTS=${params.RUN_TESTS}"   // 07-02
                mavenTecnoShop 'clean compile'
            }
        }

        stage('Checks') {
            failFast true
            parallel {
                stage('Tests') {
                    when {
                        expression { params.RUN_TESTS }
                    }
                    options {
                        timeout(time: 10, unit: 'MINUTES')
                    }
                    steps {
                        mavenTecnoShop 'test'
                        recordCoverage(
                            tools: [[parser: 'JACOCO', pattern: 'target/site/jacoco/jacoco.xml']],
                            id: 'jacoco',
                            name: 'Coverage (JaCoCo)',
                            sourceCodeRetention: 'LAST_BUILD',
                            qualityGates: [
                                [metric: 'LINE',   baseline: 'PROJECT', threshold: 70.0, criticality: 'UNSTABLE'],
                                [metric: 'BRANCH', baseline: 'PROJECT', threshold: 60.0, criticality: 'UNSTABLE']
                            ]
                        )
                    }
                    post {
                        always {
                            junit testResults: 'target/surefire-reports/*.xml', allowEmptyResults: false
                        }
                        failure {
                            echo 'The tests failed: check the Test Result page of the build.'
                        }
                    }
                }
                stage('Dependency analysis') {
                    options {
                        timeout(time: 5, unit: 'MINUTES')
                    }
                    steps {
                        mavenTecnoShop goals: 'dependency:tree -DoutputFile=dependencies.txt', label: 'Dependency tree'
                        archiveArtifacts artifacts: 'dependencies.txt'
                    }
                }
            }
        }

        stage('Integration tests') {
            when {
                expression { params.RUN_TESTS }
            }
            options {
                timeout(time: 10, unit: 'MINUTES')
            }
            steps {
                mavenTecnoShop goals: 'failsafe:integration-test failsafe:verify', label: 'Integration tests'
            }
            post {
                always {
                    junit testResults: 'target/failsafe-reports/TEST-*.xml', allowEmptyResults: false
                }
            }
        }

        stage('Package') {                                                     // 07-02: before the analysis
            steps {
                mavenTecnoShop '-DskipTests package'
                infoBuild application: 'orders-api', version: env.APP_VERSION, image: "${env.IMAGE}:${env.IMAGE_TAG}"
                archiveArtifacts artifacts: 'target/*.jar,build-info.txt', fingerprint: true
                stash name: 'jar', includes: 'target/*.jar'
            }
        }

        stage('Smoke') {                                                       // 07-02: before the analysis
            options {
                timeout(time: 3, unit: 'MINUTES')
            }
            steps {
                smokeSpringBoot extraPath: '/api/orders', expectedText: 'SHIPPED'
            }
        }

        stage('Quality analysis') {
            when {
                allOf {
                    branch 'main'
                    expression { params.RUN_TESTS }
                }
            }
            options {
                timeout(time: 10, unit: 'MINUTES')
            }
            steps {
                withSonarQubeEnv('sonar-tecnoshop') {
                    mavenTecnoShop goals: 'sonar:sonar', label: 'SonarQube analysis'
                }
            }
        }

        stage('Quality Gate') {
            when {
                allOf {
                    branch 'main'
                    expression { params.RUN_TESTS }
                }
            }
            options {
                timeout(time: 5, unit: 'MINUTES')
            }
            steps {
                waitForQualityGate abortPipeline: true
            }
        }

        stage('Publish') {
            when {
                allOf {
                    expression { params.RUN_TESTS }
                    anyOf {
                        allOf {
                            branch 'main'
                            expression { env.APP_VERSION.endsWith('-SNAPSHOT') }
                        }
                        tag pattern: 'v\\d+\\.\\d+\\.\\d+', comparator: 'REGEXP'
                    }
                }
            }
            options {
                timeout(time: 5, unit: 'MINUTES')
            }
            steps {
                milestone(label: 'Publish')                                    // 07-02
                sh label: 'Check that the tag matches the version', script: '''
                    if [ -n "${TAG_NAME:-}" ] && [ "$TAG_NAME" != "v$APP_VERSION" ]; then
                        echo "ERROR: the tag $TAG_NAME does not match the pom version ($APP_VERSION)"
                        exit 1
                    fi
                '''
                mavenTecnoShop goals: '-DskipTests -Dmaven.install.skip=true deploy',
                               settings: 'maven-settings-tecnoshop-publish',
                               label: 'Publish to Nexus'
            }
        }

        stage('Deploy to dev') {
            when {
                allOf {                                                        // 07-02: no ENVIRONMENT
                    branch 'main'
                    expression { params.RUN_TESTS }
                }
            }
            options {
                timeout(time: 5, unit: 'MINUTES')
            }
            environment {
                DEV_SERVER = 'dev-01.tecnoshop.local'
            }
            steps {
                unstash 'jar'
                sshagent(credentials: ['ssh-dev']) {
                    sh label: 'Deploy to dev-01 over SSH', script: 'sh deploy/deploy.sh "$DEV_SERVER"'
                }
            }
        }

        stage('Trigger CD') {                                                  // 07-02
            when {
                allOf {
                    tag pattern: 'v\\d+\\.\\d+\\.\\d+', comparator: 'REGEXP'
                    expression { params.RUN_TESTS }
                }
            }
            steps {
                script {
                    def sha256 = sh(script: 'sha256sum target/orders-api-*.jar | cut -d " " -f 1',
                                    returnStdout: true, label: 'SHA-256 of the published jar').trim()
                    build job: '/orders-delivery/orders-api-cd',
                          wait: false,
                          parameters: [
                              string(name: 'VERSION', value: env.APP_VERSION),
                              string(name: 'SHA256', value: sha256)
                          ]
                    currentBuild.description = "${currentBuild.description} → orders-api-cd"
                }
            }
        }
    }

    post {
        always {
            notifyTeam channel: '#ci-orders', email: '[email protected]'
        }
        cleanup {
            cleanWs()
        }
    }
}

Commit the change, together with the pom.xml and application.properties changes, on a feature/ci-design branch with its PR. The PR build will show the new stage order in Stage View; after merging, the main build will deploy to dev-01 a jar whose /actuator/info already reports its version.

Common Mistakes and Tips

  • Cutting tests on PRs to meet the time target: the failure shows up on main, where it blocks everyone. Measure first and speed up the slow stage (parallelize, move it, add executors).
  • abortPrevious: true on main too: one merge right after another could abort the first build halfway through Publish or Deploy to dev.
  • Forgetting the queue when measuring feedback: the PR author is waiting from the moment of the push, not from when the first stage starts. queueDurationMillis tells you.
  • Adding clean halfway through the pipeline: it deletes the JaCoCo report and the classes; SonarQube would analyze without coverage.
  • Writing build job: 'orders-api-cd' without a path: from a multibranch job, the name is resolved relative to the orders-api folder. Use the absolute path with a leading slash.
  • wait: true in Trigger CD: the tag build would hold an executor until someone approved production, possibly for hours.
  • Exposing every Actuator endpoint (exposure.include=*) just to see info: env, configprops or heapdump would reveal the service's configuration and memory. Expose only what you need.
  • Tip: review the durations table once a month at the team meeting. Pipelines get slower little by little, and nobody notices until feedback takes twenty minutes.

Exercises

Exercise 1. Use wfapi/describe to get the per-stage durations of the last five builds of a PR and of main (hint: .../job/main/<number>/wfapi/describe). Calculate the average per stage, compare it with the table in the lesson and say which stage you would tackle first if the average PR went over 10 minutes, and what you would do with it.

Exercise 2. Apply the lesson's Jenkinsfile. On a PR, push twice 20 seconds apart; then merge two PRs in a row into main. Describe what happens to the builds in each case, looking at the console of the aborted build. What would happen on dev-01 if main used abortPrevious: true?

Exercise 3. Diego proposes: "To make PRs faster, let's run only Build and Tests on PRs; integration tests and Smoke, only on main." Write Laura's reasoned reply, using data from the durations table.

Solutions

Solution 1. For each build, curl -s -u ... "$JENKINS_URL/job/orders-api/job/main/<n>/wfapi/describe" | jq -r '.stages[] | "\\(.name)\t\\(.durationMillis)"', and an average per stage name (grouping with jq, or in a spreadsheet). Bear in mind that Stage View and its API do not represent parallel branches well: depending on the plugin version, you may only see Checks with the duration of the whole group (that of its slowest branch, Tests); the per-branch detail is in Pipeline Graph View. With the lesson's values, the first candidate is Checks (1:30) and then Integration tests (1:00). Options, from least to most effort: running the unit tests in parallel within Maven (Surefire configuration, parallel and threadCount, if the tests are independent); moving Integration tests into Checks as a third parallel branch (only if they do not compete with the unit tests for the same target/, which you would have to verify); and, if the queue is the cause, more executors or agents. Before anything else, check queueDurationMillis: if the wait is in minutes, no stage optimization will solve it.

Solution 2. On the PR, the second push triggers a build that aborts the previous one instantly; the console of the first one shows a message saying it was interrupted because there is a newer build, and the build turns gray (ABORTED). The GitHub check reflects the result of the latest one. On main, the second build waits in the queue (Waiting for next available executor or a message saying a build is already in progress) and starts when the first one finishes; both publish and deploy in order. With abortPrevious: true on main, the second merge could abort the first build in the middle of Deploy to dev: the script might have copied the jar without restarting, or restarted without finishing the health check, and dev-01 would be left in an unverified state until the second build finished. On top of that, the SNAPSHOT of the first commit would never get published.

Solution 3. "I understand the intention, but the numbers do not justify it and the risk does. The integration tests and the smoke test add up to 1:35 of the PR's 4:40: without them we would drop to about 3 minutes, when the target is 10 and we are already under half of it. In exchange, an integration failure (a badly mapped endpoint, a configuration that prevents startup) would no longer be caught on the PR and would show up on main, where it breaks everyone's build, blocks merges under our rules and forces us to revert. The cost of a broken main is measured in person-hours; the cost of a PR that takes a minute and a half longer is nothing if you do something else in the meantime. If one day PRs get close to 10 minutes, the first thing will be to measure which stage is growing and parallelize it or speed it up, not to remove tests."

Conclusion

The orders-api commit stage is no longer a pile of pieces but an explicit design. You have a table of what runs on PRs (everything that gives feedback: build, tests, integration, packaging and smoke), on main (plus quality, publication of the SNAPSHOT and continuous deployment to dev) and on tags (full tests, publication of the release and triggering of CD), a target of under 10 minutes for PRs and the way to measure it with Pipeline Graph View, Stage View and wfapi/describe, queue included. The stages are ordered by cost and likelihood of failure (Package and Smoke before SonarQube), PRs abort their previous build with disableConcurrentBuilds(abortPrevious: env.CHANGE_ID != null) while main is built in series with a milestone in Publish, compiled output is reused with a single clean and the caches are identified. The ENVIRONMENT parameter is gone, the jar knows its version thanks to build-info and /actuator/info, and the build of every tag triggers orders-api-cd with the version and the SHA-256 of the tested jar. You have also set the team rules for when main breaks and revisited the catalog-web CI. All that is left is for that trigger to have a destination: in Setting Up a CD Pipeline you will create orders-api-cd, which will take each release from Nexus to staging, put it through acceptance tests and leave it one approval away from production.

© Copyright 2026. All rights reserved