TecnoShop's logistics team is back with its shipments-api service. In Pipeline Best Practices, Laura reviewed its first Jenkinsfile and found seventeen problems: a plain-text password, tests disabled by default, production as the default target, an input that held an executor, publishing from any branch... That Jenkinsfile was written from outside the platform, without its conventions or its building blocks. Now you are going to do it properly and from scratch: bring shipments-api onto TecnoShop's CI/CD platform from start to finish, with everything you have learned in the course. It is a capstone project in phases, each with requirements and acceptance criteria you can verify, a rubric for self-assessment, hints if you get stuck and a reference solution with the key files explained. And it has one central idea: reusing what already exists instead of copying it, because a second service is the moment when a platform proves whether it is a platform or a collection of special cases.

The Brief and How to Approach the Project

shipments-api manages order shipments: which carrier handles each order and what state it is in. It is a REST microservice in Java 21 + Spring Boot 3 + Maven (with ./mvnw), repository tecnoshop/shipments-api, main branch main, port 8082. Endpoints: GET /api/shipments (with an optional ?orderId= filter), GET /api/shipments/{id} and /actuator/health.

The logistics team's brief, in their own words: "We want the same thing orders-api has: every PR tested, main deployed to dev automatically, and releases reaching staging and production with approval and rollback. And we want to know what is going on in #ci-shipments."

How to approach it:

  • In your lab, on the platform you have built: Jenkins with JCasC and seed-jobs, the kubernetes cloud with kind, Nexus, SonarQube, the registry and, if you set them up, the staging-01, prod-01, prod-02 and lb containers from modules 6 and 7.
  • Phase by phase, in order: each one builds on the previous one. Do not move on to the next one without meeting the acceptance criteria.
  • Everything through PRs: in shipments-api, in jenkins-config and in jenkins-shared-lib. If your lab has no reviewers, review each PR yourself with the checklist from 04-07 before merging.
  • If a piece does not exist in your lab (for example, the production servers), implement the Jenkins part and verify as far as you can; the rubric takes this into account.
  • Try each phase before looking at the reference solution. The hints come before the solution precisely for that reason.

The Target Architecture

flowchart TD
    DEV["Shipments team<br/>PR in tecnoshop/shipments-api"] -->|"webhook"| MB["shipments-api multibranch<br/>(Job DSL)"]
    MB -->|"PR, main, vX.Y.Z"| POD["CI pod<br/>maven + kaniko + jnlp"]
    POD --> SQ["SonarQube<br/>shipments-api project"]
    POD --> NX["Nexus: jar, SBOM<br/>registry: image"]
    POD -->|"main: kubeconfig-shipments"| K8S["tecnoshop-dev<br/>shipments-api Deployment"]
    POD -->|"vX.Y.Z tag"| CD["shipments-delivery/shipments-api-cd<br/>deliverTecnoShop (tecnoshop-lib v1.8.0)"]
    NX --> CD
    CD -->|"ssh-staging"| ST["staging-01:8082"]
    CD -->|"approval + ssh-production"| PR["prod-01, prod-02:8082<br/>behind lb.tecnoshop.local"]
    MB --> SL["Slack #ci-shipments"]
    CD --> SL
    MB --> PM["Prometheus / Grafana<br/>ShipmentsMainBroken alert"]

Phase 1: Repository and Minimal Code

Requirements

  • A private repository tecnoshop/shipments-api with a protected main (PRs with review and the required Jenkins check, like protect-main in 06-01) and a CODEOWNERS file that assigns ci/, k8s/, Dockerfile and Jenkinsfile to the platform team as well as to the shipments team (07-05).
  • A Maven project com.tecnoshop:shipments-api:1.0.0-SNAPSHOT with the wrapper, Spring Boot 3, Java 21, server.port=8082, Actuator with build-info (07-02), JaCoCo, Failsafe, Dependency-Check, CycloneDX, SonarQube properties and distributionManagement pointing to Nexus.
  • The minimal code from the reference solution (section 13), completed with at least: one unit test per case (list, filter by order, get an existing shipment, get a missing shipment) and one integration test with MockMvc.
  • A Dockerfile (non-root user, HEALTHCHECK, OCI labels) and a .dockerignore, like the ones for orders-api in 08-01.

Acceptance criteria

  • [ ] ./mvnw -B verify finishes green on your machine and generates target/shipments-api-1.0.0-SNAPSHOT.jar, target/site/jacoco/jacoco.xml and target/bom.json.
  • [ ] java -jar target/shipments-api-*.jar responds on http://localhost:8082/api/shipments with three shipments, and /actuator/health responds with UP.
  • [ ] gitleaks detect finds no secrets in the repository.
  • [ ] A direct push to main is rejected by the branch protection.

Phase 2: Onboarding onto the Platform

Requirements

  • A PR in tecnoshop/jenkins-config that, without touching anything by hand in the interface:
    • adds the shipments-api multibranch job (with tag discovery) to jobs/multibranch.groovy;
    • creates the shipments-delivery folder with shipments-api-cd and shipments-api-rollback, reusing the orders-delivery definition instead of copying it;
    • adds the shipments-developer item role (pattern shipments-.*) and extends qa to shipments;
    • extends the TecnoShop view.
  • The tecnoshop-jenkins GitHub App installed on the repository, and the webhook configured with github-webhook-secret.
  • The shipments-api project in SonarQube with the "TecnoShop" Quality Gate.
  • In Nexus, a check that jenkins-deployer can publish com/tecnoshop/shipments-api and that jenkins-push can publish shipments-api to the registry.
  • The folder credentials the project will need, created through the written procedure (never in Git): kubeconfig-shipments in the shipments-api folder (phase 4), and ssh-staging and ssh-production in shipments-delivery (phase 5).

Acceptance criteria

  • [ ] After merging, seed-jobs finishes green and shipments-api, shipments-delivery/shipments-api-cd and shipments-delivery/shipments-api-rollback appear; the orders-delivery jobs remain intact (neither disabled nor with lost parameters).
  • [ ] As a user with the shipments-developer role, you can see and trigger shipments-api, you cannot see orders-api, and you have neither Configure nor Replay.
  • [ ] A push to a branch triggers its build within seconds (a delivery in Recent Deliveries with a 200 response).
  • [ ] The jenkins-config CI passes (valid YAML, test startup).

Phase 3: CI with tecnoshop-lib

Requirements

  • A declarative Jenkinsfile in the root, with the library at a fixed version, an agent in a pod (ci/pod-ci.yaml), and the stages and rules from the table in 07-02: on PRs, main and tags, build, unit tests with coverage (UNSTABLE below TecnoShop's thresholds), integration tests, package, smoke and image with Trivy; in parallel with the tests, Dependency-Check (with the nightly database from 09-03), gitleaks and trivy config; on main only, SonarQube and Quality Gate; on main and tags, publishing the jar, the SBOM and the image.
  • Decide and justify whether you use individual steps from tecnoshop-lib or the pipelineJavaTecnoShop template (04-06).
  • No secrets in the Jenkinsfile; no Groovy interpolation in sh with external data; a timeout on the pipeline and on every stage that could hang.

Acceptance criteria

  • [ ] A PR with a broken test goes red (FAILURE) with the Jenkins check in GitHub, and the Test Result page shows the test.
  • [ ] A PR that drops coverage below the threshold goes yellow (UNSTABLE).
  • [ ] A green main build publishes shipments-api-1.0.0-SNAPSHOT to maven-snapshots and the image registry.tecnoshop.local/shipments-api:<version>-<build>, with its digest in build-info.txt.
  • [ ] Adding a file with a fictitious secret to a PR makes the Secrets stage fail.
  • [ ] The Jenkinsfile passes the linter from 03-06 and the checklist from 04-07.
  • [ ] An average PR gets its result in less than 10 minutes.

Phase 4: Continuous Deployment to tecnoshop-dev

Requirements

  • Manifests in k8s/ (ConfigMap; a Deployment with a zero-downtime rolling update, startup, readiness and liveness probes, and a security context compatible with the restricted level; and a Service).
  • A dedicated deployment identity in the tecnoshop-dev namespace, deploy-shipments, which can only modify the shipments-api Deployment, and its kubeconfig as the folder credential kubeconfig-shipments.
  • A stage on main that deploys by digest with deployToKubernetes, with automatic rollback if the rollout does not complete.

Acceptance criteria

  • [ ] After a main build, kubectl -n tecnoshop-dev rollout status deployment/shipments-api reports success and kubectl -n tecnoshop-dev get deploy shipments-api -o jsonpath='{.spec.template.spec.containers[0].image}' shows the build's @sha256: reference.
  • [ ] kubectl auth can-i with the deploy-shipments kubeconfig: patch deployment/shipments-api → yes; patch deployment/orders-api → no; get secrets → no.
  • [ ] A change that breaks the readiness probe makes the build fail and leaves the previous revision in service.
  • [ ] The orders-api multibranch job cannot use kubeconfig-shipments.

Phase 5: Release CD with Approval and Rollback

Requirements

  • When vX.Y.Z is tagged, the CI publishes the release and triggers shipments-delivery/shipments-api-cd with VERSION and SHA256, without waiting.
  • The CD follows TecnoShop's model (07-03, 07-04): validate parameters, download and verify the release, review the SBOM's vulnerabilities, staging with a lock and shipments-api's own acceptance tests, approval without an executor and with a change reference, node-by-node rolling deployment to production with automatic rollback in reverse order, and notifications.
  • Mandatory reuse: shipments-api cannot have a copy of orders-api's ci/Jenkinsfile.cd with the names changed. Design how both share the delivery process.
  • shipments-delivery/shipments-api-rollback with confirmation and a mandatory reason.
  • On the servers, shipments-api with its own runtime user, its own deployment user (deploy-shipments) with permissions only on its own service, its systemd unit and its entry in the load balancer.

Acceptance criteria

  • [ ] git tag v1.0.0 (after changing pom.xml to 1.0.0 on a release/1.0.0 branch, as in 06-05) ends with shipments-api-cd waiting for approval and shipments-api 1.0.0 responding on staging-01:8082/actuator/info.
  • [ ] Only laura or the production-approvers group can approve; without a change reference, nothing is deployed.
  • [ ] A failure triggered on prod-02 reverts prod-02 and prod-01, leaves both in the load balancer with the previous version and sends a REVERTED notification.
  • [ ] With the ssh-production key from shipments-delivery, it is not possible to restart orders-api.service.
  • [ ] orders-api-cd keeps working exactly as before after the change (an orders-api release reaches staging).

Phase 6: Notifications

Requirements

  • A #ci-shipments channel with TecnoShop's Slack app invited.
  • The common rules from 06-07: only main notifies the team (changes of state, not every green build); PRs, in GitHub; the CD, every actionable milestone (pending approval, deployed, failed, reverted, canceled).
  • Email to the shipments team ([email protected]) for main failures.

Acceptance criteria

  • [ ] Breaking main produces one notification in #ci-shipments; the next broken build does not repeat it; fixing it produces a "fixed" notification.
  • [ ] A broken PR does not post to #ci-shipments.
  • [ ] The CD posts to #ci-shipments when it is pending approval, with a direct link to the form.

Phase 7: Observability and Backups

Requirements

  • In Grafana, the service's panels (last result of main, average PR and main duration, failed builds in 24 hours) filtered by shipments-.*.
  • A warning alert, ShipmentsMainBroken, if shipments-api/main has been red for more than an hour, addressed to the shipments team, with its runbook linked.
  • The backups from 05-03 cover the new items, and the jenkins-config folder credentials procedure includes those of shipments-api and shipments-delivery.

Acceptance criteria

  • [ ] With main red for more than an hour (you can lower for to 5 minutes to test it), Alertmanager sends the alert to the shipments team's receiver.
  • [ ] In a Jenkins restored from the latest backup (05-03), the shipments-delivery credentials and kubeconfig-shipments exist and can be decrypted, and the shipments-api history is present.
  • [ ] The jenkins-config README.md lists the new folder credentials with their ID, location, source of the value and owner.

Phase 8: Documentation

Requirements

  • ci/README.md in shipments-api: what the pipeline does in each type of build, how a release is done, which credentials and resources it uses (by ID, never values), where to look when it fails and who to turn to.
  • docs/runbook.md in shipments-api with at least three procedures: main is red (ShipmentsMainBroken), a failed CD in production and a manual rollback.

Acceptance criteria

  • [ ] Someone who has not been involved can do a release by following only ci/README.md.
  • [ ] The runbook annotation of ShipmentsMainBroken points to a section that exists.
  • [ ] No document contains secrets, not even fictitious ones that look real.

Assessment Rubric

Criterion Minimum acceptable Excellent
Code and repository Builds, tests green, protected branch Meaningful tests for every case, coverage above the thresholds, CODEOWNERS and required checks
As code Multibranch job, folder and role created with Job DSL and JCasC, no clicks The delivery definition generalized for N services; the seed run does not alter orders-delivery; jenkins-config CI green
CI pipeline Every stage from the table in 07-02 with its conditions PR feedback under 10 minutes, measured; the 04-07 checklist with no exceptions; stage names identical to those of orders-api
Security No secrets in Git or in the log; gitleaks, Dependency-Check, Trivy and SBOM Least privilege verified (auth can-i, SSH keys per service, folder credentials); no new script approvals
Deployment to dev Deployment by digest with deployToKubernetes Automatic rollback verified by causing a failure; manifests that meet restricted
Delivery and rollback CD with staging, approval and production A process shared with orders-api without copying; automatic rollback in reverse order tested; orders-api migrated with no change in behavior
Reuse tecnoshop-lib steps instead of copied blocks A justified steps/template decision; a new library version with tests and documentation (vars/*.txt); consumers updated through PRs
Notifications main and CD notifications in #ci-shipments No noise: one notification per change of state; direct links to the build and to the approval
Observability and continuity Panels and alert configured Alert tested end to end; restore verified with the new credentials
Documentation ci/README.md and runbook present Someone else does a release and a rollback using only the documentation

Count your "excellents": with 7 or more, your platform is at level 3 of the maturity model from 09-01 in all of its technical dimensions.

Hints by Phase

  • Phase 1: start from the orders-api pom.xml as it ended up in modules 6 and 7 and change only the coordinates, the name and the description; if you find yourself rewriting plugins, something is wrong. The port goes in application.properties, not in the code.
  • Phase 2: the solution to exercise 2 in 08-03 already gave you half of this phase. For the delivery folder, notice that jobs/orders-delivery.groovy defines a function with the name orders-api baked into it: generalize it. If you rename the file, check in the seed log that the existing jobs are updated and not disabled.
  • Phase 3: the pipelineJavaTecnoShop template has no security, image or deployment. Ask yourself what would happen if you extended it to cover everything, with the steps vs. templates table from 04-06 in front of you.
  • Phase 4: the lab/kind/tecnoshop-dev.yaml file from 08-02 is your template; the security trick is in resourceNames. Remember that the first deployment has no previous revision to go back to.
  • Phase 5: the CD, unlike the CI, is company policy: the same promotion model for everyone. That changes the answer to "steps or template?". And look at what orders-api has hard-coded in its deploy/ scripts.
  • Phase 6: do not write a single slackSend: notifyTeam and notifyDeployment already exist.
  • Phase 7: the jenkins_job label in the metrics includes the branch (shipments-api/main). To route the alert, use a custom label in the rule and a route in Alertmanager.
  • Phase 8: the runbook template from 09-01. Write the README with whoever will read it on a Friday at 18:00 in mind.

Reference Solution

Repository Structure and Minimal Code

shipments-api/
├── .github/CODEOWNERS
├── .mvn/ , mvnw, mvnw.cmd          # Maven Wrapper (git update-index --chmod=+x mvnw)
├── pom.xml                         # the orders-api one with other coordinates
├── Dockerfile, .dockerignore
├── Jenkinsfile                     # CI (phase 3)
├── ci/
│   ├── pod-ci.yaml                 # CI pod (same as orders-api)
│   ├── Jenkinsfile.cd              # 2 lines: deliverTecnoShop (phase 5)
│   ├── Jenkinsfile.rollback        # 2 lines: rollbackTecnoShop (phase 5)
│   ├── acceptance.sh               # shipments-api acceptance criteria
│   └── README.md                   # phase 8
├── deploy/shipments-api.service    # systemd unit installed by the platform team
├── docs/runbook.md                 # phase 8
├── k8s/{configmap,deployment,service}.yaml
└── src/...

src/main/java/com/tecnoshop/shipments/Shipment.java and ShipmentController.java:

package com.tecnoshop.shipments;

public record Shipment(Long id, Long orderId, String carrier, String status) {
}
package com.tecnoshop.shipments;

import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/shipments")
public class ShipmentController {

    private static final List<Shipment> SHIPMENTS = List.of(
            new Shipment(1L, 1001L, "TransRapido", "PREPARING"),
            new Shipment(2L, 1002L, "LogiNorte", "IN_TRANSIT"),
            new Shipment(3L, 1003L, "TransRapido", "DELIVERED"));

    @GetMapping
    public List<Shipment> list(@RequestParam(required = false) Long orderId) {
        if (orderId == null) {
            return SHIPMENTS;
        }
        return SHIPMENTS.stream().filter(s -> s.orderId().equals(orderId)).toList();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Shipment> get(@PathVariable Long id) {
        return SHIPMENTS.stream()
                .filter(s -> s.id().equals(id))
                .findFirst()
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
}
  • record Shipment: an immutable type with its four fields, like Order in 01-04. The data is fictitious and static: the goal of the project is the platform, not the domain.
  • list(@RequestParam(required = false) Long orderId): with no parameter it returns everything; with ?orderId=1002, only that order's shipments.
  • get: 200 with the shipment or 404, just as in orders-api.
  • IN_TRANSIT is the text the Smoke stage will look for.
  • ShipmentsApiApplication (the class with @SpringBootApplication and main), application.properties (server.port=8082, plus management.endpoint.health.probes.enabled=true if your version does not expose the probes by default) and the tests are left to you. Complete ShipmentControllerTest with the four cases and ShipmentControllerIT with MockMvc, like OrderControllerIT in 06-03.

jenkins-config: Jobs, Delivery Folder and Roles

In jobs/multibranch.groovy, one more line in the list, which is what "a new project is one line" means (08-03):

    [name: 'shipments-api',  tags: true,
     description: 'CI for shipments-api (Java 21, Spring Boot). Pipeline: the repository Jenkinsfile.'],

jobs/orders-delivery.groovy is renamed to jobs/delivery.groovy and generalized:

// Delivery folders (CD and rollback) for the services that deploy to virtual machines.
// Processed by seed-jobs. Folder credentials (ssh-staging, ssh-production) are NOT managed here: see README.md.

def deliveryPipeline(String jobPath, String application, String descriptionText, String scriptFile, Closure jobParameters) {
    pipelineJob(jobPath) {
        description(descriptionText)
        parameters(jobParameters)              // mirrors the parameters of the Jenkinsfile (08-03)
        definition {
            cpsScm {
                scm {
                    git {
                        remote {
                            url("https://github.com/tecnoshop/${application}.git")
                            credentials('github-tecnoshop')
                        }
                        branch('*/main')
                    }
                }
                scriptPath(scriptFile)
                lightweight(true)
            }
        }
    }
}

def deliveryFolder(Map service) {
    String folderName = "${service.domain}-delivery"
    String app = service.application

    folder(folderName) {
        description("Delivery (CD) pipelines for ${app}. Staging and production credentials. Owner: ${service.owner}.")
    }

    deliveryPipeline("${folderName}/${app}-cd", app,
            "CD for ${app}: Nexus release → staging → acceptance → approval → production.",
            'ci/Jenkinsfile.cd') {
        stringParam {
            name('VERSION'); defaultValue(''); trim(true)
            description('Release X.Y.Z published in maven-releases (e.g. 1.1.0). Never a SNAPSHOT.')
        }
        stringParam {
            name('SHA256'); defaultValue(''); trim(true)
            description('SHA-256 of the jar tested in the tag build. Filled in by CI; empty when triggered by hand.')
        }
    }

    deliveryPipeline("${folderName}/${app}-rollback", app,
            "Manual rollback of ${app} in production.",
            'ci/Jenkinsfile.rollback') {
        stringParam {
            name('TARGET_VERSION'); defaultValue(''); trim(true)
            description('Empty: the previous version on each node. Or a version present in releases/ on the servers (e.g. 1.1.0).')
        }
        stringParam {
            name('REASON'); defaultValue(''); trim(true)
            description('Reason for the rollback and incident reference.')
        }
    }
}

[
    [domain: 'orders',    application: 'orders-api',    owner: 'Laura'],
    [domain: 'shipments', application: 'shipments-api', owner: 'Laura'],
].each { service ->
    deliveryFolder(service)
}
  • The same idea as multibranchTecnoShop: a function and a list. A third service that deploys to virtual machines is one more line.
  • Renaming the file does not affect the jobs: Job DSL identifies jobs by their full name, not by the file that generates them. Since orders-delivery/orders-api-cd is still generated in the same way, the seed run updates it (with no changes) instead of disabling it. Check this in the seed log: it must not appear in the list of removed jobs.
  • The folder name carries the domain prefix: shipments-delivery fits the shipments-.* pattern, just as orders-delivery fits orders-.* (07-03).

In casc/jenkins.yaml, the new role and the extended qa role (and, in jobs/views.groovy, the regex changed to (orders|catalog|shipments)-.*):

          - name: "shipments-developer"
            pattern: "shipments-.*"
            permissions:
              - "Job/Read"
              - "Job/Build"
              - "Job/Cancel"
              - "Job/Workspace"
            entries:
              - group: "shipments-developers"
          - name: "qa"
            pattern: "(orders|catalog|shipments)-.*"
            permissions:
              - "Job/Read"
              - "Job/Build"
            entries:
              - user: "marta"
  • group: "shipments-developers": effective once TecnoShop has SSO (05-02); in the meantime, individual user: entries are added, with their passwords as secrets, just like diego.

The CI Jenkinsfile: Individual Steps, and Why

Decision: individual steps from tecnoshop-lib, not the pipelineJavaTecnoShop template. The template from 04-06 was designed for "simple" services: build, test and package. shipments-api needs security, an image, quality analysis, publishing, deployment to Kubernetes and triggering the CD; cramming all of that into the template would turn it into the template "full of if (config.x)" that 04-06 warned about. It is only honest to admit, though, that this Jenkinsfile is 90% the same as the orders-api one: with a third Java service just like them, the duplication would justify a new, complete template (for example, pipelineServiceTecnoShop) designed from the three real cases, not from an imagined one. The rule of three: generalize when there are three consumers, not before.

@Library('[email protected]') _

pipeline {
    agent {
        kubernetes {
            cloud 'kubernetes'
            yamlFile 'ci/pod-ci.yaml'
            defaultContainer 'maven'
        }
    }

    options {
        timestamps()
        timeout(time: 30, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
        disableConcurrentBuilds(abortPrevious: env.CHANGE_ID != null)
        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. Security checks always run.')
    }

    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/shipments-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}"
                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 }
                    }
                }
                stage('Dependency analysis') {
                    options { timeout(time: 15, unit: 'MINUTES') }
                    steps {
                        mavenTecnoShop goals: 'dependency:tree -DoutputFile=dependencies.txt', label: 'Dependency tree'
                        withCredentials([string(credentialsId: 'nvd-api-key', variable: 'NVD_API_KEY')]) {
                            mavenTecnoShop goals: 'dependency-check:check -DautoUpdate=false',
                                           label: 'Known vulnerabilities (OWASP Dependency-Check, nightly database)'
                        }
                    }
                    post {
                        always {
                            archiveArtifacts artifacts: 'dependencies.txt,target/dependency-check-report.html', allowEmptyArchive: true
                            dependencyCheckPublisher pattern: 'target/dependency-check-report.xml', unstableTotalMedium: 1
                        }
                    }
                }
                stage('Secrets') {
                    steps {
                        container('jnlp') { scanSecrets() }
                    }
                }
                stage('Secrets in history') {
                    when { allOf { branch 'main'; triggeredBy 'TimerTrigger' } }
                    steps {
                        container('jnlp') { scanSecrets history: true, report: 'gitleaks-history.json' }
                    }
                }
                stage('Container configuration') {
                    steps {
                        container('jnlp') {
                            sh label: 'Dockerfile and Kubernetes manifests (trivy config)',
                               script: 'trivy config --severity HIGH,CRITICAL --exit-code 1 --quiet Dockerfile k8s/'
                        }
                    }
                }
            }
        }

        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') {
            steps {
                mavenTecnoShop '-DskipTests package'
                infoBuild application: 'shipments-api', version: env.APP_VERSION, image: "${env.IMAGE}:${env.IMAGE_TAG}"
                archiveArtifacts artifacts: 'target/*.jar,target/bom.json,build-info.txt', fingerprint: true
                stash name: 'jar', includes: 'target/*.jar'
            }
        }

        stage('Smoke') {
            options { timeout(time: 3, unit: 'MINUTES') }
            steps {
                container('jnlp') {
                    smokeSpringBoot extraPath: '/api/shipments', expectedText: 'IN_TRANSIT'
                }
            }
        }

        stage('Image') {
            options { timeout(time: 15, unit: 'MINUTES') }
            steps {
                buildImage engine: 'kaniko', image: env.IMAGE, tag: env.IMAGE_TAG, version: env.APP_VERSION
            }
        }

        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 -Dsonar.userHome=/cache/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: 10, unit: 'MINUTES') }
            steps {
                milestone(label: 'Publish')
                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 (jar and SBOM)'
                publishImage engine: 'kaniko', image: env.IMAGE, tag: env.IMAGE_TAG,
                             extraTags: env.TAG_NAME ? [env.APP_VERSION] : []
            }
        }

        stage('Deploy to dev') {
            when { allOf { branch 'main'; expression { params.RUN_TESTS } } }
            options { timeout(time: 5, unit: 'MINUTES') }
            steps {
                container('jnlp') {
                    deployToKubernetes credential: 'kubeconfig-shipments', namespace: 'tecnoshop-dev',
                                       deployment: 'shipments-api', image: env.IMAGE_DIGEST, manifests: 'k8s'
                }
            }
        }

        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/shipments-api-*.jar | cut -d " " -f 1',
                                    returnStdout: true, label: 'SHA-256 of the published jar').trim()
                    build job: '/shipments-delivery/shipments-api-cd', wait: false,
                          parameters: [string(name: 'VERSION', value: env.APP_VERSION),
                                       string(name: 'SHA256', value: sha256)]
                    currentBuild.description = "${currentBuild.description} → shipments-api-cd"
                }
            }
        }
    }

    post {
        always {
            notifyTeam channel: '#ci-shipments', email: '[email protected]'
        }
    }
}

What changes compared with the orders-api Jenkinsfile at the end of module 8, and what deliberately does not change:

Changes Why
[email protected] The version with deliverTecnoShop and the improvements from 09-03 (Trivy not updating its database during builds)
IMAGE, application, extraPath, expectedText, channel and email The service's own data
-DautoUpdate=false and -Dsonar.userHome=/cache/sonar The optimizations from 09-03, from day one
A single deployment stage for dev, on Kubernetes shipments-api is born on Kubernetes for dev; there is no dev-01 for it (next section)
kubeconfig-shipments and /shipments-delivery/shipments-api-cd Its identity and its folder
Does not change Why
Stage names, order and conditions The conventions from 04-07 and the table from 07-02: dashboards, wfapi queries and runbooks work the same way for both services
Coverage and vulnerability thresholds They are TecnoShop's quality policy, not a team preference
notifyTeam and its rules The same rules for everyone (06-07)

ci/pod-ci.yaml is the orders-api one (08-02), changing only the tecnoshop/project: shipments-api label, which makes it possible to tell its pods apart in the cluster.

Deployment to tecnoshop-dev: Identity and Manifests

lab/kind/tecnoshop-dev-shipments.yaml in jenkins-config (applied by the platform team, not by the pipeline):

apiVersion: v1
kind: ServiceAccount
metadata:
  name: deploy-shipments
  namespace: tecnoshop-dev
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: deploy-shipments
  namespace: tecnoshop-dev
rules:
  - apiGroups: ["apps"]
    resources: ["deployments"]
    resourceNames: ["shipments-api"]
    verbs: ["get", "patch", "update"]
  - apiGroups: ["apps"]
    resources: ["deployments"]
    verbs: ["create", "list", "watch"]
  - apiGroups: ["apps"]
    resources: ["replicasets"]
    verbs: ["get", "list", "watch"]
  - apiGroups: [""]
    resources: ["configmaps", "services"]
    verbs: ["get", "list", "create", "patch", "update"]
  - apiGroups: [""]
    resources: ["pods", "pods/log", "events"]
    verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: deploy-shipments
  namespace: tecnoshop-dev
subjects:
  - kind: ServiceAccount
    name: deploy-shipments
    namespace: tecnoshop-dev
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: deploy-shipments
---
apiVersion: v1
kind: Secret
metadata:
  name: deploy-shipments-token
  namespace: tecnoshop-dev
  annotations:
    kubernetes.io/service-account.name: deploy-shipments
type: kubernetes.io/service-account-token
  • It is the deploy-orders file from 08-02 with other names. The piece that provides the isolation is resourceNames: ["shipments-api"]: with this identity, the orders-api Deployment cannot be touched.
  • A known limitation worth writing down: configmaps and services are not restricted by name (for the same reason as in 08-02, create does not support resourceNames), so in theory this identity could modify another service's ConfigMap in the namespace. For dev that is acceptable; for staging and production on Kubernetes, one namespace per service (or GitOps, 09-04) would solve it.
  • The kubeconfig is built as in 08-02 and stored as a Secret file with the ID kubeconfig-shipments in the shipments-api multibranch folder.

The manifests in k8s/ are the orders-api ones with these changes (and no others):

Element orders-api shipments-api
metadata.name and the app.kubernetes.io/name label orders-api shipments-api
ConfigMap orders-api-config with application-dev.properties shipments-api-config, same content with info.environment=dev
containerPort 8081 8082
Configuration mount and SPRING_CONFIG_ADDITIONAL_LOCATION /etc/orders-api /etc/shipments-api
runAsUser, probes, RollingUpdate, readOnlyRootFilesystem, resources Identical

The decision not to deploy shipments-api to dev-01 over SSH: the service is born on Kubernetes for dev, which is where the platform is heading (08-05). The price is less parity between dev (Kubernetes) and staging/production (virtual machines); it is accepted temporarily because the CD runs the acceptance tests in staging, on the same platform as production, and it is recorded as debt in docs/decisions/.

Shared Delivery: tecnoshop-lib v1.8.0

When you look at orders-api's ci/Jenkinsfile.cd and deploy/*.sh, two kinds of content appear:

  • What belongs to orders-api: its name, its port, its channel and its acceptance criteria (ci/acceptance.sh, Marta's criteria).
  • What belongs to TecnoShop: the promotion model, the release verification, the rolling deployment with the load balancer, the rollback in reverse order, the deployment window, the approval with a change reference, the servers' host keys.

The second kind is company policy: it must be the same for every service and change in a single place. That is why, here, the answer to "steps or template?" is the opposite of the CI one: template. Laura publishes tecnoshop-lib v1.8.0 with:

New content What it is
vars/deliverTecnoShop.groovy The ci/Jenkinsfile.cd from 07-03/07-04 turned into a parameterized template
vars/rollbackTecnoShop.groovy The ci/Jenkinsfile.rollback from 07-04, parameterized in the same way
vars/prepareDeployment.groovy Writes the library's scripts and known_hosts to deploy/ in the workspace
resources/com/tecnoshop/deploy/* fetch-release.sh, deploy.sh, check-health.sh, revert.sh, load-balancer.sh, deploy-window.sh, review-vulnerabilities.sh and known_hosts, parameterized

The scripts had the service hard-coded. The parameterization:

In orders-api In the library
target/orders-api-*.jar, /opt/orders-api, orders-api.jar, orders-api.service $APPLICATION in all those paths and names
http://$SERVER:8081 http://$SERVER:$PORT
DEPLOY_USER="deploy" DEPLOY_USER="${DEPLOY_USER:-deploy}"
/usr/local/sbin/orders-api-lb /usr/local/sbin/$APPLICATION-lb
.../com/tecnoshop/orders-api/$VERSION/orders-api-$VERSION.jar .../com/tecnoshop/$APPLICATION/$VERSION/$APPLICATION-$VERSION.jar

resources/com/tecnoshop/deploy/deploy.sh, as a complete example:

#!/bin/sh
# Deploys the jar of a TecnoShop service to a server over SSH and checks its health. (tecnoshop-lib)
# Usage: deploy/deploy.sh <server>
# Requires: APPLICATION, PORT, the SSH key loaded and APP_VERSION plus BUILD_NUMBER, or DEPLOY_VERSION.
# Optional: DEPLOY_USER (default: deploy).
set -eu

SERVER="$1"
case "$APPLICATION" in ""|*[!a-z0-9-]*) echo "ERROR: invalid APPLICATION: '$APPLICATION'" >&2; exit 2 ;; esac
case "$PORT" in ""|*[!0-9]*) echo "ERROR: invalid PORT: '$PORT'" >&2; exit 2 ;; esac

DEPLOY_USER="${DEPLOY_USER:-deploy}"
BASE="/opt/$APPLICATION"
LOCAL_JAR=$(ls target/"$APPLICATION"-*.jar)
DEPLOY_VERSION="${DEPLOY_VERSION:-${APP_VERSION}-${BUILD_NUMBER}}"
RELEASE_PATH="$BASE/releases/$APPLICATION-${DEPLOY_VERSION}.jar"
SSH_OPTS="-o BatchMode=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=deploy/known_hosts -o ConnectTimeout=10"

echo "==> Copying $LOCAL_JAR to $SERVER:$RELEASE_PATH"
scp $SSH_OPTS "$LOCAL_JAR" "$DEPLOY_USER@$SERVER:$RELEASE_PATH"

echo "==> Activating $APPLICATION $DEPLOY_VERSION on $SERVER"
ssh $SSH_OPTS "$DEPLOY_USER@$SERVER" "
    set -e
    cd $BASE
    CURRENT=\$(readlink $APPLICATION.jar || true)
    if [ -n \"\$CURRENT\" ] && [ \"\$CURRENT\" != '$RELEASE_PATH' ]; then
        ln -sfn \"\$CURRENT\" $APPLICATION.jar.previous
    fi
    ln -sfn '$RELEASE_PATH' $APPLICATION.jar
    sudo systemctl restart $APPLICATION.service
    PREVIOUS=\$(readlink $APPLICATION.jar.previous || true)
    ls -1t releases/$APPLICATION-*.jar | tail -n +6 | while read -r f; do
        if [ \"$BASE/\$f\" != \"\$PREVIOUS\" ]; then rm -f \"\$f\"; fi
    done
"

if ! sh deploy/check-health.sh "http://$SERVER:$PORT" "$APP_VERSION"; then
    ssh $SSH_OPTS "$DEPLOY_USER@$SERVER" "systemctl status $APPLICATION.service --no-pager" || true
    exit 1
fi
  • It is the deploy.sh from 07-04, line by line, with the substitutions from the table.
  • The two new validations (the case statements on APPLICATION and PORT) are essential: those variables are now inserted into the remote command. Only lowercase letters, digits and hyphens are accepted in the name, and only digits in the port, so that no value can alter what runs on the server.
  • known_hosts also lives in the library: the host keys of dev-01, staging-01, prod-01, prod-02 and lb belong to the platform, and they are now verified and changed in one place.

vars/prepareDeployment.groovy:

/**
 * Puts TecnoShop's deployment scripts and the servers' known_hosts in deploy/.
 * They need in the environment: APPLICATION and PORT (and DEPLOY_USER if it is not 'deploy').
 *
 *   prepareDeployment()
 */
def call() {
    for (String file : ['fetch-release.sh', 'deploy.sh', 'check-health.sh', 'revert.sh',
                        'load-balancer.sh', 'deploy-window.sh', 'review-vulnerabilities.sh', 'known_hosts']) {
        writeFile file: "deploy/${file}", text: libraryResource("com/tecnoshop/deploy/${file}")
    }
}

vars/deliverTecnoShop.groovy, the delivery template:

/**
 * TecnoShop delivery (CD) pipeline for Java services deployed to virtual machines:
 * Nexus release → vulnerabilities → staging + acceptance → approval → production (rolling) with rollback.
 *
 *   @Library('[email protected]') _
 *   deliverTecnoShop application: 'shipments-api', port: 8082, channel: '#ci-shipments',
 *                    deployUser: 'deploy-shipments'
 *
 * Contract with the service repository: ci/acceptance.sh <base-url> <version> <environment>; optional .trivyignore.
 */
def call(Map config = [:]) {
    for (String required : ['application', 'port', 'channel']) {
        if (!config[required]) {
            error "deliverTecnoShop: missing parameter \"${required}\""
        }
    }
    if (!(config.application ==~ /[a-z0-9-]+/) || !(config.port.toString() ==~ /\d+/)) {
        error 'deliverTecnoShop: "application" only accepts lowercase letters, digits and hyphens, and "port" only digits'
    }
    String application = config.application
    String channel     = config.channel
    String approvers   = config.submitter ?: 'laura,production-approvers'
    String lockStaging = config.stagingResource ?: 'env-staging'
    String lockProd    = config.productionResource ?: 'env-production'
    String prodNodes   = (config.productionNodes ?: ['prod-01.tecnoshop.local', 'prod-02.tecnoshop.local']).join(' ')

    pipeline {
        agent none

        options {
            timestamps()
            buildDiscarder(logRotator(numToKeepStr: '100'))
            skipDefaultCheckout()
        }

        parameters {
            string(name: 'VERSION', defaultValue: '', trim: true,
                   description: 'Release X.Y.Z published in maven-releases (e.g. 1.1.0). Never a SNAPSHOT.')
            string(name: 'SHA256', defaultValue: '', trim: true,
                   description: 'SHA-256 of the jar tested in the tag build. Filled in by CI; empty when triggered by hand.')
        }

        environment {
            NEXUS_URL        = "${config.nexusUrl ?: 'http://nexus:8081'}"
            APPLICATION      = "${application}"
            PORT             = "${config.port}"
            DEPLOY_USER      = "${config.deployUser ?: 'deploy'}"
            STAGING_SERVER   = "${config.stagingServer ?: 'staging-01.tecnoshop.local'}"
            PRODUCTION_NODES = "${prodNodes}"
            LOAD_BALANCER    = "${config.loadBalancer ?: 'lb.tecnoshop.local'}"
            APP_VERSION      = "${params.VERSION}"
            DEPLOY_VERSION   = "${params.VERSION}"
        }

        stages {
            stage('Validate parameters') {
                steps {
                    script {
                        if (!(params.VERSION ==~ /\d+\.\d+\.\d+/)) {
                            error "VERSION must have the form X.Y.Z (e.g. 1.1.0); received '${params.VERSION}'"
                        }
                        if (params.SHA256 && !(params.SHA256 ==~ /[0-9a-f]{64}/)) {
                            error 'SHA256, if given, must be 64 lowercase hexadecimal characters'
                        }
                        currentBuild.displayName = "#${env.BUILD_NUMBER} · ${params.VERSION}"
                    }
                }
            }

            stage('Fetch release') {
                agent { label 'linux' }
                options { timeout(time: 5, unit: 'MINUTES') }
                steps {
                    checkout scm
                    prepareDeployment()
                    sh label: 'Download from Nexus and verify (jar and SBOM)', script: 'sh deploy/fetch-release.sh "$APP_VERSION"'
                    fingerprint "target/${application}-*.jar"
                    stash name: 'release', includes: "target/${application}-*.jar,target/bom.json,.trivyignore,deploy/**,ci/**"
                }
                post { cleanup { cleanWs() } }
            }

            stage('Vulnerability review') {
                agent { label 'linux' }
                options { timeout(time: 10, unit: 'MINUTES') }
                steps {
                    unstash 'release'
                    sh label: 'Trivy on the release SBOM', script: 'sh deploy/review-vulnerabilities.sh'
                }
                post { cleanup { cleanWs() } }
            }

            stage('Staging') {
                agent { label 'linux' }
                options {
                    lock(resource: lockStaging)
                    timeout(time: 15, unit: 'MINUTES')
                }
                stages {
                    stage('Deploy to staging') {
                        steps {
                            milestone(label: 'Staging')
                            script { env.CURRENT_ENV = 'staging' }
                            unstash 'release'
                            sshagent(credentials: ['ssh-staging']) {
                                sh label: 'Deploy to staging over SSH', script: 'sh deploy/deploy.sh "$STAGING_SERVER"'
                            }
                        }
                        post {
                            failure {
                                sshagent(credentials: ['ssh-staging']) {
                                    sh label: 'Rollback of staging', script: 'sh deploy/revert.sh "$STAGING_SERVER" || true'
                                }
                            }
                        }
                    }
                    stage('Acceptance tests') {
                        steps {
                            sh label: 'Service acceptance criteria',
                               script: 'sh ci/acceptance.sh "http://$STAGING_SERVER:$PORT" "$APP_VERSION" staging'
                            notifyDeployment application: application, channel: channel, environment: 'staging',
                                             version: params.VERSION, result: 'PENDING'
                        }
                    }
                }
                post { cleanup { cleanWs() } }
            }

            stage('Approval') {
                options { timeout(time: 24, unit: 'HOURS') }
                input {
                    message "Deploy the ${application} version validated in staging to production?"
                    ok 'Deploy to production'
                    submitter "${approvers}"
                    submitterParameter 'APPROVED_BY'
                    parameters {
                        string(name: 'CHANGE_REFERENCE', defaultValue: '',
                               description: 'Reference of the approved change and a short reason (e.g. CHG-2026-0157: filter by order)')
                    }
                }
                steps {
                    script {
                        if (!env.CHANGE_REFERENCE?.trim()) {
                            error 'Approval without a change reference: not deploying to production.'
                        }
                        env.APPROVAL = "${env.APPROVED_BY} (${env.CHANGE_REFERENCE.trim()})"
                        currentBuild.description = "${application} ${params.VERSION} · approved by ${env.APPROVAL}"
                    }
                }
            }

            stage('Deploy to production') {
                agent { label 'linux' }
                options {
                    lock(resource: lockProd)
                    timeout(time: 20, unit: 'MINUTES')
                }
                steps {
                    milestone(label: 'Production')
                    script { env.CURRENT_ENV = 'production' }
                    unstash 'release'
                    sh label: 'Deployment window', script: 'sh deploy/deploy-window.sh'
                    sshagent(credentials: ['ssh-production']) {
                        script {
                            deployToProductionWithRollback(env.PRODUCTION_NODES.tokenize(' '))
                        }
                    }
                }
                post { cleanup { cleanWs() } }
            }
        }

        post {
            success {
                notifyDeployment application: application, channel: channel, environment: 'production',
                                 version: params.VERSION, detail: "Approved by ${env.APPROVAL}"
            }
            failure {
                notifyDeployment application: application, channel: channel,
                                 environment: env.CURRENT_ENV ?: 'preparation', version: params.VERSION,
                                 result: env.REVERTED ? 'REVERTED' : 'FAILED',
                                 detail: env.REVERTED == 'yes' ? 'Automatic rollback completed' : env.REVERTED
            }
            aborted {
                notifyDeployment application: application, channel: channel, environment: 'production',
                                 version: params.VERSION, result: 'CANCELLED'
            }
        }
    }
}

// Node-by-node rolling deployment; if anything fails, reverts the nodes already touched in reverse order (07-04).
def deployToProductionWithRollback(List<String> nodes) {
    List touched = []
    try {
        for (String nodeName : nodes) {
            touched << nodeName
            stepOnNode(nodeName, 'deploy.sh', true)
        }
        sh label: 'Production verification through the load balancer',
           script: 'sh ci/acceptance.sh "http://$LOAD_BALANCER" "$APP_VERSION" production'
    } catch (err) {
        echo "Production failure: ${err}. Reverting, in reverse order: ${touched.reverse().join(', ')}"
        List notReverted = []
        for (String nodeName : touched.reverse()) {
            try {
                stepOnNode(nodeName, 'revert.sh', false)
            } catch (revertErr) {
                echo "ERROR: could not revert ${nodeName}; it stays OUT of the load balancer (${revertErr})"
                notReverted << nodeName
            }
        }
        env.REVERTED = notReverted ? "partial; not reverted: ${notReverted.join(', ')}" : 'yes'
        throw err
    }
}

// Removes the node from the load balancer, runs the given script and puts the node back.
def stepOnNode(String nodeName, String script, boolean pause) {
    withEnv(["NODE=${nodeName}", "NODE_SCRIPT=${script}"]) {
        sh label: "${nodeName}: remove from the load balancer", script: 'sh deploy/load-balancer.sh remove "$NODE"'
        if (pause) {
            sleep time: 10, unit: 'SECONDS'
        }
        sh label: "${nodeName}: ${script}", script: 'sh "deploy/$NODE_SCRIPT" "$NODE"'
        sh label: "${nodeName}: put back into the load balancer", script: 'sh deploy/load-balancer.sh restore "$NODE"'
    }
}

The essentials, given that the logic is the one from 07-03 and 07-04:

  • Configuration validation at the start: application and port will end up in paths and commands, like VERSION. The template fails before creating the pipeline if they are invalid.
  • Local variables in the pipeline: application, channel, approvers, lockStaging, lockProd and prodNodes are Groovy variables of call, which the declarative pipeline can see because it is defined inside the function, like application in pipelineJavaTecnoShop from 04-06. Whatever the scripts need to see goes into environment.
  • The contract with the service is small and documented: ci/acceptance.sh with three arguments and, optionally, .trivyignore. The library provides everything else with prepareDeployment().
  • The locks are shared by default (env-staging, env-production): there will never be two deployments of different services at the same time in the same environment, and one service's acceptance tests will never get mixed up with another's restart. The price is waiting a few minutes when they coincide, and a rollback of one service having to wait for a deployment of the other to finish. If that ever became a nuisance, the stagingResource and productionResource parameters allow per-service resources.
  • deployToProductionWithRollback and stepOnNode: the updateNode and revertNode functions from the original Jenkinsfile.cd, merged into one (they only differed in the script and in the pause). The script name reaches the shell through withEnv, not through interpolation.
  • No preserveStashes, for the reason given in 07-03: to prevent a Restart from Stage from production that would skip the approval.

vars/rollbackTecnoShop.groovy follows the same pattern with the Jenkinsfile.rollback from 07-04: validation, confirmation with input (30 minutes), the production lock, checkout scm, prepareDeployment() and the loop with load-balancer.sh and revert.sh. With a deliberate revision of an earlier decision: 07-04 left the rollback without the library so that it would have fewer dependencies in an emergency. Laura revisits that: the rollback already depends on GitHub (because of checkout scm), the library is loaded from the same GitHub at a fixed version, and in exchange the rollback uses exactly the same scripts as the deployment it reverts. What it does keep is the absence of mandatory notifications: if Slack fails during an emergency, the rollback is not affected. The decision, with its reasoning, goes into docs/decisions/.

With all of that, the shipments-api files:

// ci/Jenkinsfile.cd
@Library('[email protected]') _
deliverTecnoShop application: 'shipments-api', port: 8082, channel: '#ci-shipments', deployUser: 'deploy-shipments'
// ci/Jenkinsfile.rollback
@Library('[email protected]') _
rollbackTecnoShop application: 'shipments-api', port: 8082, deployUser: 'deploy-shipments'

And the orders-api ones, in a PR of their own that is also part of the project:

// orders-api's ci/Jenkinsfile.cd, which goes from about 200 lines to this
@Library('[email protected]') _
deliverTecnoShop application: 'orders-api', port: 8081, channel: '#ci-orders'
  • orders-api deletes its copies of the scripts in deploy/ (it keeps orders-api.service, which the platform team installs) and, in its CI Jenkinsfile, the Deploy to dev stage calls prepareDeployment() with APPLICATION=orders-api and PORT=8081 in its environment.
  • It is validated like any other library change (04-06): first, an orders-api branch with @Library('tecnoshop-lib@feature/shared-delivery'); then, a real run of orders-api-cd with the current release up to Approval (redeploying the same version to staging is harmless), which is then aborted; only then is v1.8.0 published and the two PRs merged.

On the servers, the platform team prepares shipments-api just as it prepared orders-api in 07-03: Java 21, a shipments user that runs the service, /opt/shipments-api/releases and /etc/shipments-api (with PORT=8082 and its application-<environment>.properties), the shipments-api.service unit from the repository, and a deployment user of its own, deploy-shipments, whose only sudo permission is systemctl restart shipments-api.service (and, on lb, /usr/local/sbin/shipments-api-lb, a copy of the load balancer program for the shipments-api upstream). The ssh-staging and ssh-production credentials in shipments-delivery are new keys for deploy-shipments: the same IDs as in orders-delivery (the template does not change), a different value and a different scope.

Notifications, Observability and Backups

The notifications need no new code: notifyTeam channel: '#ci-shipments', email: '[email protected]' in the CI and channel: '#ci-shipments' in the CD. All you need is to create the channel and invite the Slack app (without that, slackSend fails and the steps log it in the console without breaking the build).

In monitoring/jenkins-alerts.yml:

      - alert: ShipmentsMainBroken
        expr: default_jenkins_builds_last_build_result_ordinal{jenkins_job="shipments-api/main"} == 2
        for: 1h
        labels:
          severity: warning
          team: shipments
        annotations:
          summary: "shipments-api/main has been red for more than an hour"
          runbook: "https://github.com/tecnoshop/shipments-api/blob/main/docs/runbook.md#main-is-red"

And in monitoring/alertmanager.yml, one route per team under the general route:

route:
  receiver: devops-team
  group_by: ["alertname"]
  routes:
    - matchers: ['team="shipments"']
      receiver: shipments-team

receivers:
  - name: devops-team
    # ... as in 05-05 ...
  - name: shipments-team
    email_configs:
      - to: [email protected]
        from: [email protected]
        smarthost: smtp.tecnoshop.local:25
        require_tls: false
  • default_jenkins_builds_last_build_result_ordinal ... == 2: the same metric as the failed jobs table from 05-05; 2 is FAILURE.
  • for: 1h: a main that is broken for a few minutes is normal (someone is fixing it); for an hour, it is not (07-02 set the team rules for when main breaks).
  • labels.team and routes.matchers: the custom label decides who receives the alert. Platform alerts keep going to devops-team.
  • annotations.runbook: the link that 09-01 requires for every alert.

In Grafana, a new row on the dashboard with the queries from 05-05 filtered with jenkins_job=~"shipments-api/.*". And for backups: backup-jenkins.sh copies the whole volume, so the new history and credentials are already included; what gets added is the check in the quarterly drill (the shipments-delivery credentials and kubeconfig-shipments can be decrypted in the restored Jenkins) and the three folder credentials in the procedure in the jenkins-config README.md. SonarQube and Nexus have their own backups, outside the scope of Jenkins but not outside the scope of the platform team.

Documentation

ci/README.md (excerpt):

# shipments-api pipeline

## What runs and when
| Build         | Stages                                                                  |
| PR            | Build, Checks, Integration tests, Package, Smoke, Image |
| main          | The above + Quality analysis, Quality Gate, Publish (SNAPSHOT), Deploy to dev (Kubernetes) |
| Tag vX.Y.Z    | The PR stages + Publish (release) and Trigger CD (shipments-delivery/shipments-api-cd) |

## How to do a release
1. Branch release/X.Y.Z: ./mvnw versions:set -DnewVersion=X.Y.Z, PR and merge.
2. git tag vX.Y.Z && git push origin vX.Y.Z; in Jenkins, shipments-api → Tags → Build Now.
3. The CD deploys to staging and posts in #ci-shipments; laura or production-approvers approve.
4. Next SNAPSHOT on main (X.Y.(Z+1)-SNAPSHOT) through a PR.

## Resources it uses (by ID; the values are not in any repository)
kubeconfig-shipments (shipments-api folder), ssh-staging and ssh-production (shipments-delivery folder),
nvd-api-key, nexus-deployer (via maven-settings-tecnoshop-publish), registry-tecnoshop, sonar-token.

## When it fails
Build console (red stage) → docs/runbook.md → #ci-support (platform).

docs/runbook.md, with the template from 09-01 and three sections: main is red (open the build, identify the stage, apply the broken-main rules, revert the commit if it is not fixed within an hour), failed CD in production (read the FAILED or REVERTED notification; if it says "partial", a node is out of the load balancer: check with load-balancer.sh status and call the platform team) and manual rollback (trigger shipments-delivery/shipments-api-rollback with the reason, confirm, and verify /actuator/info through lb.tecnoshop.local).

Common Mistakes and Tips

  • Copying orders-api's Jenkinsfile.cd and changing the names: it works today and diverges tomorrow. When Laura changes the deployment window or the rollback, someone will have to remember to do it in N places. The delivery process is policy: a single place.
  • Generalizing the CI too "for symmetry": each service's CI has legitimate nuances; with two consumers, a complete template would be premature. Generalize what is policy and what is repeated three times.
  • Parameterizing scripts without validating the parameters: APPLICATION ends up in a remote command; without the validation, an unexpected value would be a command injection in production.
  • Reusing orders-api's SSH keys for shipments-api: a convenience that breaks isolation; one key per service and environment, with a deployment user that can only touch its own service.
  • Forgetting the parameters in Job DSL when generalizing the delivery folder: Build with Parameters would disappear and triggering from CI would fail (08-03).
  • Breaking orders-api while creating shipments-api: migrating the existing consumer is part of the work, with its own real test.
  • Considering a phase done without its acceptance criterion: "I think it works" is not evidence; kubectl auth can-i, the webhook delivery or the restored Jenkins are.
  • Tip: when you finish, time how long it would take you to onboard a third service. If the answer is "an afternoon and three small PRs", the platform works like a product.

Exercises

Exercise 1. Using the criteria from the steps vs. templates table in 04-06, explain why the reference solution uses individual steps for the CI and a template for the CD. What would have to happen for the CI to move to a template as well?

Exercise 2. A developer on the shipments team opens a PR in shipments-api that changes ci/Jenkinsfile.cd to @Library('tecnoshop-lib@my-branch') _, where my-branch is a library branch with a deliverTecnoShop that skips the approval. List all the platform barriers that prevent this from reaching production.

Exercise 3. The first main build of shipments-api fails in Deploy to dev: the rollout does not complete and the rollback fails too. Explain why this happens on the first deployment, what state is left in tecnoshop-dev and what you would do.

Solutions

Solution 1. CI: the services have legitimately different needs (smoke checks with their own paths and texts, perhaps databases for the integration tests in the future, another language), the readability of the Jenkinsfile in the repository is valuable to the team that maintains it, and a change to a template would affect every team's entire pipeline; with individual steps, the common policy (coverage, security, notifications) is already centralized in the steps. CD: the promotion model is company policy and must be identical (maximum standardization), flexibility is not wanted (a team skipping staging is not an option), and the risk of a "template full of ifs" is low because the real differences are data (name, port, channel, user). For the CI to move to a template: a third service with the same shape, a review of the three pipelines showing that the differences are data and not structure, and a template designed from those cases, with an easy way out for any service that stops fitting (going back to individual steps), as 04-06 anticipates.

Solution 2. (1) The shipments-delivery/shipments-api-cd job reads ci/Jenkinsfile.cd from main, not from the PR branch: the change has no effect until it is merged. (2) main is protected: the PR needs a review, and CODEOWNERS assigns ci/ to the platform team, which would not approve it. (3) Only the platform team can write to the jenkins-shared-lib repository: the developer cannot create my-branch there (04-06). (4) Even if it did run, the shipments-api multibranch job (where the PR does get built) has no access to ssh-production, which is in the shipments-delivery folder. (5) Without Configure or Replay on the CD job, nobody on the team can change its definition or run a modified script (07-03). (6) The ssh-production key in shipments-delivery only allows touching shipments-api. (7) Audit Trail and the Git history would leave a trace of any attempt. Security does not rest on a single barrier, but on several independent ones.

Solution 3. On the first deployment there is no previous revision of the Deployment: if the rollout does not complete (for example, because the readiness probe points to a path that does not exist or the container port does not match the application's), kubectl rollout undo has nowhere to go back to and fails, as 08-02 warned. What is left is a shipments-api Deployment with pods that never become ready (in dev, acceptable: there was nothing there before). What to do: the diagnostics step of deployToKubernetes will already have shown the pods and the events; kubectl -n tecnoshop-dev describe pod -l app.kubernetes.io/name=shipments-api and the container logs will tell you whether it is the probe, the port (8082 vs. 8081 copied from orders-api is the usual suspect), the configuration or the security context; it is fixed in a PR, and the next main build deploys correctly. Prevention: test the manifests in the PR with trivy config (already in place) and, if you like, with a kubectl apply --dry-run=server against the cluster.

Conclusion

You have brought shipments-api onto TecnoShop's platform from start to finish, and this time properly from the very beginning: a protected repository with its minimal code and its tests; onboarding in jenkins-config that generalized the delivery folder instead of copying it; a CI with the tecnoshop-lib steps that applies, from the very first build, the course's conventions, quality and security controls and optimizations; continuous deployment to tecnoshop-dev with an identity that can only touch its own resources; a release CD with approval and rollback that orders-api and shipments-api now share, thanks to the deliverTecnoShop template and the parameterized scripts of v1.8.0; notifications in #ci-shipments without a single new line of code; an alert with its runbook and its route to the team; verified backups; and the documentation someone else needs to do a release without asking. The rubric tells you where you stand, and the rule of three tells you when to generalize again. With this project you have shown what you can do with Jenkins; the last lesson of the course is about how to keep learning and about the community that keeps it alive, in Jenkins Community and Resources.

© Copyright 2026. All rights reserved