Since the previous lesson, the build of every orders-api vX.Y.Z tag publishes the release to Nexus and triggers a job that does not exist yet: /orders-delivery/orders-api-cd. In this lesson you will create it. It will be the second half of the deployment pipeline from 07-01: it receives a version, downloads exactly that jar from Nexus and verifies that it is the one that was tested, deploys it to staging-01.tecnoshop.local, runs the acceptance tests defined by Marta, waits for an approval without holding any executor and, once approved, takes it to the two production servers. Along the way you will prepare the servers with their per-environment configuration, create credentials that only this pipeline can use, coordinate builds with lock and milestone, record every deployment and decide who can trigger and who can approve.

What orders-api-cd Does

sequenceDiagram
    actor D as Diego
    participant CI as orders-api (tag v1.1.0)
    participant N as Nexus (maven-releases)
    participant CD as orders-api-cd
    participant S as staging-01
    actor L as Laura
    participant P as prod-01 and prod-02
    D->>CI: git push origin v1.1.0 and Build Now under Tags
    CI->>CI: build, test, package, smoke
    CI->>N: publish orders-api-1.1.0.jar
    CI->>CD: build with VERSION=1.1.0 and SHA256 (no waiting)
    CD->>N: download the jar and its .sha1
    CD->>CD: verify the Nexus SHA-1 and the CI SHA-256
    CD->>S: deploy.sh with ssh-staging
    CD->>S: acceptance tests
    CD-->>L: Slack #ci-orders: pending approval
    L->>CD: approve with the change reference
    CD->>P: deploy.sh on prod-01 and then on prod-02 (ssh-production)
    CD-->>D: Slack #ci-orders: deployed to production

Three design decisions, before getting into the details:

  • A pipeline separate from the CI one, with its own Jenkinsfile (ci/Jenkinsfile.cd, in the same repository). CI runs on every commit and takes minutes; CD runs once per release and can wait hours for an approval. Mixing them would fill the Jenkinsfile with conditions and put the production credentials within reach of PR builds.
  • It never rebuilds: the input is a version, and the artifact comes from Nexus.
  • The same thing in every environment: the same deploy/deploy.sh from 06-06 deploys to dev-01, staging-01, prod-01 and prod-02. Only the server, the credential and the server's configuration change.

The staging and Production Servers

Server Environment Credential Who uses it
dev-01.tecnoshop.local dev ssh-dev (global) Every main build of the multibranch job
staging-01.tecnoshop.local staging ssh-staging (orders-delivery folder) Only orders-api-cd
prod-01.tecnoshop.local and prod-02.tecnoshop.local production ssh-production (orders-delivery folder) Only orders-api-cd, after approval
lb.tecnoshop.local production ssh-production nginx load balancer in front of the two servers; the pipeline will use it in 07-04

Laura prepares staging-01, prod-01 and prod-02 exactly like dev-01 in 06-06: Java 21, an orders user that runs the service, a deploy user that deploys with a single sudo (systemctl restart orders-api.service), the /opt/orders-api/releases and /etc/orders-api directories, and the deploy/orders-api.service unit installed and enabled. Environment parity: the same system, the same Java, the same unit.

Per-Environment Configuration, Outside the Artifact

The only thing that changes between servers is the configuration, which lives in /etc/orders-api/ and never in the jar. There are two files:

/etc/orders-api/orders-api.env, which the systemd unit reads (EnvironmentFile). On staging-01:

PORT=8081
JAVA_OPTS="-Xms256m -Xmx512m"
SPRING_PROFILES_ACTIVE=staging
SPRING_CONFIG_ADDITIONAL_LOCATION=optional:file:/etc/orders-api/
  • SPRING_PROFILES_ACTIVE=staging: activates the Spring Boot staging profile (in production, production).
  • SPRING_CONFIG_ADDITIONAL_LOCATION=optional:file:/etc/orders-api/: Spring Boot will also look for configuration files in that directory, in addition to the ones inside the jar. With the profile active, it will load application-staging.properties from there. optional: keeps the application from failing to start if the directory has no files. Since the variables in the EnvironmentFile reach the process as environment variables, Spring picks them up without touching the unit.

/etc/orders-api/application-staging.properties:

# orders-api configuration for staging. Managed by the platform team, not by the repository.
info.environment=staging
management.info.env.enabled=true
logging.level.com.tecnoshop=DEBUG
  • info.environment=staging: a property that /actuator/info will show; management.info.env.enabled=true turns on publishing of the info.* properties (off by default). That way anyone can check which environment a service is in, and so can the acceptance tests.
  • logging.level.com.tecnoshop=DEBUG: more detail in staging; in application-production.properties, INFO.
  • When orders-api gets a database, its URL will go here and its password in a separate file (or in a secrets manager), with 0640 permissions for root:orders, just like the .env file.

The orders-api-1.1.0.jar jar is identical on all three servers; each server tells it who it is.

Optional Lab: staging-01, prod-01 and prod-02

If you are using the dev-01 container from 06-06, copy its directory to create a parameterized image that works for the three new servers:

cd ~/tecnoshop-jenkins/lab
cp -r dev-01 app-server
mkdir -p app-server/keys

Replace app-server/Dockerfile with this version (the changes from the dev-01 one are commented):

# LAB ONLY: simulates staging-01, prod-01 and prod-02 (no systemd)
FROM eclipse-temurin:21-jre

# Parameters for each server (new)
ARG HOST_NAME
ARG ENVIRONMENT
ARG PUBLIC_KEY

RUN echo "Building $HOST_NAME ($ENVIRONMENT)" \
 && apt-get update \
 && apt-get install -y --no-install-recommends openssh-server sudo curl procps \
 && rm -rf /var/lib/apt/lists/* \
 && mkdir -p /run/sshd \
 && ssh-keygen -A \
 && useradd --system --home-dir /opt/orders-api --shell /usr/sbin/nologin orders \
 && useradd --create-home --shell /bin/bash deploy \
 && mkdir -p /opt/orders-api/releases /etc/orders-api /var/log/orders-api /home/deploy/.ssh \
 && chown -R deploy:orders /opt/orders-api \
 && chmod 750 /opt/orders-api /opt/orders-api/releases \
 && chown orders:orders /var/log/orders-api \
 && chown deploy:deploy /home/deploy/.ssh \
 && chmod 700 /home/deploy/.ssh

COPY sshd-tecnoshop.conf /etc/ssh/sshd_config.d/tecnoshop.conf
COPY sudoers-deploy /etc/sudoers.d/deploy
COPY systemctl-lab.sh /usr/bin/systemctl
COPY --chown=deploy:deploy ${PUBLIC_KEY} /home/deploy/.ssh/authorized_keys

# Per-environment configuration (new: replaces the COPY of orders-api.env)
RUN printf 'PORT=8081\nJAVA_OPTS="-Xms128m -Xmx256m"\nSPRING_PROFILES_ACTIVE=%s\nSPRING_CONFIG_ADDITIONAL_LOCATION=optional:file:/etc/orders-api/\n' \
        "$ENVIRONMENT" > /etc/orders-api/orders-api.env \
 && printf 'info.environment=%s\nmanagement.info.env.enabled=true\n' \
        "$ENVIRONMENT" > "/etc/orders-api/application-$ENVIRONMENT.properties" \
 && chown root:orders /etc/orders-api/orders-api.env "/etc/orders-api/application-$ENVIRONMENT.properties" \
 && chmod 640 /etc/orders-api/orders-api.env "/etc/orders-api/application-$ENVIRONMENT.properties" \
 && chmod 440 /etc/sudoers.d/deploy \
 && chmod 755 /usr/bin/systemctl \
 && chmod 600 /home/deploy/.ssh/authorized_keys

EXPOSE 22
CMD ["/usr/sbin/sshd", "-D", "-e"]
  • ARG HOST_NAME, ENVIRONMENT and PUBLIC_KEY: values that Compose passes when building each server.
  • The first RUN starts with an echo that uses HOST_NAME. It is not decorative: Docker reuses cached layers, and without a different value per server, prod-01 and prod-02 would share the ssh-keygen -A layer and have the same host keys. Using the argument in that instruction forces one layer (and one set of keys) per server, as would happen with real machines.
  • COPY ... ${PUBLIC_KEY}: each environment authorizes its own public key.
  • The printf commands: they generate the .env file and the application-<environment>.properties file from the previous section. The systemctl-lab.sh from dev-01 already loads the .env file with set -a, so Spring gets the variables just as it would with systemd.

And in docker-compose.yml, one service per server (staging-01 is shown; prod-01 and prod-02 are the same, changing the name, the environment to production and the key to keys/ssh-production.pub):

  staging-01:
    build:
      context: ./lab/app-server
      args:
        HOST_NAME: staging-01.tecnoshop.local
        ENVIRONMENT: staging
        PUBLIC_KEY: keys/ssh-staging.pub
    image: tecnoshop/lab-staging-01:1
    container_name: staging-01
    hostname: staging-01.tecnoshop.local
    restart: unless-stopped
    networks:
      default:
        aliases:
          - staging-01.tecnoshop.local

Before building you need the public keys, which you will generate in the next section. Then: docker compose up -d --build staging-01 prod-01 prod-02. That is three more 256 MB JVMs; if you are short on memory, stop the services you are not using.

The orders-delivery Folder and Its Credentials

Why a Folder

The credentials from 04-04 have Global scope: any job can request them. That means a PR whose modified Jenkinsfile included sshagent(['ssh-production']) could use it, even though the Trust policy from 04-05 limits who can do so. For production, TecnoShop wants a stronger guarantee: that only the CD pipeline can use the staging and production keys.

Folder credentials achieve this: a credential stored in a folder is only available to the jobs inside it. The orders-api multibranch job, which is outside, cannot even see them.

  1. New Item → name orders-delivery → Folder. Description: Delivery (CD) pipelines for orders-api. Staging and production credentials. Owner: Laura.
  2. The name starts with orders- on purpose: the item roles from 05-02 (orders-developer with orders-.* and qa with (orders|catalog)-.*) are matched against the full name, and orders-delivery/orders-api-cd fits them without touching the role configuration.

The Keys

Generate one key per environment on your machine, just like ssh-dev:

ssh-keygen -t ed25519 -f ./ssh-staging -N '' -C 'jenkins-cd@tecnoshop-staging'
ssh-keygen -t ed25519 -f ./ssh-production -N '' -C 'jenkins-cd@tecnoshop-production'
cp ./ssh-staging.pub ./ssh-production.pub ~/tecnoshop-jenkins/lab/app-server/keys/

On real servers, the ssh-staging public key goes into the authorized_keys of deploy on staging-01, and the ssh-production one on prod-01, prod-02 and lb.tecnoshop.local.

In Jenkins, inside the folder: orders-delivery → Credentials → (the folder's store) → Global credentials (unrestricted) → Add Credentials:

Field ssh-staging ssh-production
Kind SSH Username with private key SSH Username with private key
ID ssh-staging ssh-production
Description SSH for deployments to staging-01. orders-delivery pipelines only. Owner: Laura. SSH for deployments to prod-01, prod-02 and lb. orders-api-cd only, after approval. Owner: Laura.
Username deploy deploy
Private Key Contents of ./ssh-staging Contents of ./ssh-production

Then:

  • Delete the global ssh-staging practice credential from 04-04 (Manage Jenkins → Credentials, global scope): the ID now lives in the folder, and a global copy would undo the isolation. The lab-credentials job that used it will fail in that part; it has already served its purpose.
  • Delete the private keys from your machine.
  • "Global credentials (unrestricted)" is the name of the default domain inside the folder's store; it does not mean the credential is global to Jenkins.

Least privilege, to recap: with ssh-production, someone can only upload a jar to releases/, switch the link and restart orders-api.service (and, in 07-04, take a node out of the load balancer or put it back). They cannot become root, touch other services or log in to other servers.

known_hosts

Add the host keys of the three servers to deploy/known_hosts, verifying each one's fingerprint as in 06-06 (ssh-keygen -lf on the server and ssh-keyscan from the agent), with a PR that explains the change.

The orders-api-cd Job

Inside orders-delivery: New Item → name orders-api-cd → Pipeline.

Section Field Value
General Description CD for orders-api: Nexus release → staging → acceptance → approval → production.
General Do not allow concurrent builds Unchecked (coordination is done with lock and milestone, section 12)
Build Triggers None: it is triggered by the tag build or by a person
Pipeline Definition Pipeline script from SCM
Pipeline SCM → Repository URL https://github.com/tecnoshop/orders-api.git
Pipeline Credentials github-tecnoshop
Pipeline Branch Specifier */main
Pipeline Script Path ci/Jenkinsfile.cd
Pipeline Lightweight checkout Checked
  • Pipeline script from SCM from main: the delivery process is versioned and reviewed just like the code. It is the same thing you did with orders-api-pipeline in 03-01, with a different Script Path.
  • Jenkinsfile.cd and the deploy/ scripts are always taken from main, even if the version being deployed is older: the current deployment process applies to any version. The artifact, on the other hand, is the one for the requested version.
  • The parameters (VERSION, SHA256) are defined by Jenkinsfile.cd itself. As with any pipeline, Jenkins does not know about them until the first build: run it with Build Now, it will fail validation because it has no version, and from then on Build with Parameters will appear.

Parameters and Validation

    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.')
    }
  • trim: true: removes leading and trailing spaces, a typical copy-and-paste mistake.
  • SHA256 is optional so that a person can trigger CD by hand (for example, to redeploy a version): in that case only the Nexus checksum will be verified.

The first stage validates the parameters without an agent:

        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}"
                }
            }
        }
  • ==~: the Groovy operator that checks whether the whole string matches the regular expression. \d+\.\d+\.\d+ requires three numbers separated by dots: 1.1.0 passes; 1.1.0-SNAPSHOT, v1.1.0 or 1.1 do not.
  • It is the first line of defense: the value of VERSION will end up in the scripts' paths and URLs, and validating its form rules out unexpected values (such as ../ or ; rm).
  • currentBuild.displayName: the build shows up in the history as #12 · 1.1.0 instead of #12. Knowing at a glance which version each build deployed is half the record-keeping done.
  • No agent: with a global agent none (section 10), these steps do not need an executor.

Fetching the Release from Nexus and Verifying It

The download is a versioned script, deploy/fetch-release.sh, under the usual rule: the pipeline orchestrates, the tool does the work.

#!/bin/sh
# Downloads the jar of an orders-api release from Nexus and verifies its integrity.
# Usage: deploy/fetch-release.sh <version>
# Requires: NEXUS_URL. Optional: SHA256 (expected checksum, the one from the tag build).
set -eu

VERSION="$1"
case "$VERSION" in
    ""|*[!0-9.]*) echo "ERROR: invalid version: '$VERSION'" >&2; exit 1 ;;
esac

URL="$NEXUS_URL/repository/maven-releases/com/tecnoshop/orders-api/$VERSION/orders-api-$VERSION.jar"
JAR="target/orders-api-$VERSION.jar"

mkdir -p target
rm -f target/orders-api-*.jar*

echo "==> Downloading $URL"
curl --fail --silent --show-error --location --retry 3 -o "$JAR" "$URL"
curl --fail --silent --show-error --location --retry 3 -o "$JAR.sha1" "$URL.sha1"

echo "==> Verifying the SHA-1 checksum published in Nexus"
echo "$(cut -c1-40 "$JAR.sha1")  $JAR" | sha1sum -c -

if [ -n "${SHA256:-}" ]; then
    echo "==> Verifying that this is the jar tested in the tag build (SHA-256)"
    echo "$SHA256  $JAR" | sha256sum -c -
else
    echo "WARNING: no expected SHA256 (manual run); only the Nexus checksum was verified"
fi

sha256sum "$JAR"
rm -f "$JAR.sha1"
  • case ... *[!0-9.]*: a second validation, in the shell: if the version contains anything other than digits or dots, it is rejected. The script can also be run outside Jenkins, and it must not trust whoever calls it.
  • URL: the standard Maven path in a hosted repository: the groupId with slashes (com/tecnoshop), the artifactId, the version and the file. Access is anonymous read, which Laura enabled in 06-05: the CD pipeline does not need (or get) nexus-deployer, which can publish. If reading requires authentication in your organization, create a read-only Nexus user and a credential for it; never reuse the publishing one.
  • curl --fail: exits with an error if Nexus responds 404 (version not published) or any other HTTP error. --retry 3 retries transient network failures.
  • $URL.sha1: Maven publishes a SHA-1 checksum next to each file (06-05). cut -c1-40 takes the 40 characters of the checksum (some clients append the file name after it), and sha1sum -c - checks that the downloaded jar matches it. It catches corrupted or truncated downloads.
  • SHA256: the important verification. The Nexus checksum comes from the same server as the jar: if someone could replace the file in Nexus, they could also replace its .sha1. The SHA-256 that the tag build calculated comes from Jenkins, by a different route, and proves that the jar is the one that passed the tests. Cryptographic signing of artifacts, one step further, is covered in 07-05.

In the pipeline:

        stage('Fetch release') {
            agent {
                label 'linux'
            }
            options {
                timeout(time: 5, unit: 'MINUTES')
            }
            steps {
                checkout scm
                sh label: 'Download from Nexus and verify', script: 'sh deploy/fetch-release.sh "$APP_VERSION"'
                fingerprint 'target/orders-api-*.jar'
                stash name: 'release', includes: 'target/orders-api-*.jar,deploy/**,ci/**'
            }
            post {
                cleanup {
                    cleanWs()
                }
            }
        }
  • checkout scm: with skipDefaultCheckout() in the global options, the pipeline does not check out automatically in every stage with an agent; it does so once, here. That way every stage uses the same scripts, even if main changes while the build is waiting for an approval.
  • fingerprint: records the fingerprint (MD5) of the downloaded jar. Since the tag build archived the same jar with a fingerprint, the build's See Fingerprints page shows that the file is the one produced by orders-api » v1.1.0 #1: the traceability of "build once", visible in Jenkins.
  • stash name: 'release': the jar, the deployment scripts and ci/acceptance.sh travel to the following stages, which may run in another workspace or on another agent.

So that deploy.sh copies the jar with the version name (orders-api-1.1.0.jar instead of orders-api-1.1.0-<build>.jar), change one line in it:

DEPLOY_VERSION="${DEPLOY_VERSION:-${APP_VERSION}-${BUILD_NUMBER}}"
  • ${DEPLOY_VERSION:-...}: if the DEPLOY_VERSION variable exists, it is used as is; if not, the usual value is kept. SNAPSHOT deployments to dev do not change; the CD pipeline sets DEPLOY_VERSION=1.1.0.

staging: Deployment and Acceptance Tests

Marta's Criteria

The acceptance tests are not written by the developer of the change but by QA: Marta defines what any version must satisfy before approval is requested.

ID Criterion Check
A1 The service is healthy GET /actuator/health → 200 with "status":"UP"
A2 It is the requested version GET /actuator/info → "version":"<VERSION>"
A3 It uses the environment's configuration GET /actuator/info → "environment":"staging"
A4 The listing responds GET /api/orders → 200 with orders
A5 The status filter works GET /api/orders?status=SHIPPED → 200 and only SHIPPED orders
A6 An existing order can be retrieved GET /api/orders/1 → 200
A7 A missing order returns 404 GET /api/orders/999999 → 404

A2 and A3 use the info endpoint you added in 07-02. A5 tests Diego's feature from 04-05.

ci/acceptance.sh

#!/bin/sh
# orders-api acceptance tests against a deployed environment (QA criteria).
# Usage: ci/acceptance.sh <base-url> <version> <environment>
set -eu

BASE="$1"
VERSION="$2"
ENVIRONMENT="$3"
FAILURES=0
RESPONSE=$(mktemp)

check() {   # check <id> <description> <path> <expected code> [expected text]
    id="$1"; desc="$2"; path="$3"; expected="$4"; text="${5:-}"
    code=$(curl -s -o "$RESPONSE" -w '%{http_code}' --max-time 10 "$BASE$path" || true)
    if [ "$code" != "$expected" ]; then
        echo "FAIL  $id $desc: $path returned '$code' (expected $expected)"
        FAILURES=$((FAILURES + 1))
    elif [ -n "$text" ] && ! grep -qF "$text" "$RESPONSE"; then
        echo "FAIL  $id $desc: the response from $path does not contain $text"
        FAILURES=$((FAILURES + 1))
    else
        echo "OK    $id $desc"
    fi
}

check A1 'Healthy service'           /actuator/health    200 '"status":"UP"'
check A2 'Requested version'         /actuator/info      200 "\"version\":\"$VERSION\""
check A3 'Environment configuration' /actuator/info      200 "\"environment\":\"$ENVIRONMENT\""
check A4 'Order listing'             /api/orders         200 '"id":'
check A6 'Existing order'            /api/orders/1       200 '"id":1'
check A7 'Missing order'             /api/orders/999999  404

check A5 'Status filter'             '/api/orders?status=SHIPPED' 200 '"status":"SHIPPED"'
others=$(grep -o '"status":"[A-Z_]*"' "$RESPONSE" | grep -vc '"status":"SHIPPED"' || true)
if [ "$others" != "0" ]; then
    echo "FAIL  A5 Status filter: there are $others orders with a different status"
    FAILURES=$((FAILURES + 1))
fi

rm -f "$RESPONSE"
if [ "$FAILURES" -gt 0 ]; then
    echo "Acceptance NOT passed on $BASE: $FAILURES criterion/criteria not met"
    exit 1
fi
echo "Acceptance passed on $BASE (version $VERSION)"
  • check: a shell function that makes a request and compares the HTTP code and, if given, a piece of text. -o "$RESPONSE" saves the body to a temporary file; -w '%{http_code}' prints only the code; || true keeps a connection error from stopping the script (the code will be empty and will count as a failure).
  • The function does not stop at the first failure: it runs every criterion and exits with an error at the end if any failed. That way the report tells you everything that is wrong at once.
  • grep -qF: searches for the literal text (-F, no regular expressions), quietly (-q).
  • A5 in two steps: the response contains SHIPPED and, in addition, no order has a different status (grep -o extracts each "status":"..." and grep -vc counts the ones that are not SHIPPED).
  • When the list of criteria grows, it is worth migrating them to a dedicated test suite (REST Assured, Postman/Newman, Playwright) that publishes JUnit XML for the junit step. For seven checks, a readable script is enough.

The Stage

        stage('Staging') {
            agent {
                label 'linux'
            }
            options {
                lock(resource: 'env-staging')
                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-01 over SSH', script: 'sh deploy/deploy.sh "$STAGING_SERVER"'
                        }
                    }
                }
                stage('Acceptance tests') {
                    steps {
                        sh label: 'QA acceptance criteria',
                           script: 'sh ci/acceptance.sh "http://$STAGING_SERVER:8081" "$APP_VERSION" staging'
                        notifyDeployment application: 'orders-api', channel: '#ci-orders', environment: 'staging',
                                         version: params.VERSION, result: 'PENDING'
                    }
                }
            }
            post {
                cleanup {
                    cleanWs()
                }
            }
        }
  • A Staging stage with two nested stages (04-01): they share the agent, the workspace and, above all, the lock, so nobody can deploy another version to staging-01 while the acceptance tests are running.
  • script { env.CURRENT_ENV = 'staging' }: a variable that the failure notice will use to say where it happened. Assigning env.X inside script makes it available for the rest of the build.
  • sshagent(credentials: ['ssh-staging']): a folder credential is used exactly like a global one.
  • notifyDeployment ... result: 'PENDING': announces that there is a version waiting for approval (section 13).

The Approval: input Without Holding Executors

In 04-07 you saw the problem: an input inside steps with an agent holds an executor for hours. The solution is the combination this pipeline uses:

  1. agent none at the pipeline level: no stage has an executor except the ones that declare their own.
  2. The Approval stage does not declare an agent.
  3. The input is a stage directive, not a step.
        stage('Approval') {
            options {
                timeout(time: 24, unit: 'HOURS')
            }
            input {
                message 'Deploy the version validated in staging to production?'
                ok 'Deploy to production'
                submitter 'laura,production-approvers'
                submitterParameter 'APPROVED_BY'
                parameters {
                    string(name: 'CHANGE_REFERENCE', defaultValue: '',
                           description: 'Reference of the approved change and a short reason (e.g. CHG-2026-0142: filter orders by status)')
                }
            }
            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 = "orders-api ${params.VERSION} · approved by ${env.APPROVAL}"
                }
            }
        }

The directive, field by field:

Field What it does
message The text seen by whoever opens the build: the question being asked
ok The text of the approve button (by default, Proceed). Abort always appears next to it
submitter Who can approve: user IDs and/or group names, separated by commas
submitterParameter The name of a variable that will receive the ID of whoever approved
parameters Data requested at approval time, with the same syntax as build parameters

Details worth knowing:

  • Evaluation order: in a stage, the options (the timeout) are applied first, then the input is awaited, and only then is when evaluated (unless beforeInput true) and the agent allocated, if there is one. That is why the 24-hour timeout covers the wait.
  • submitter: laura is a user in the Jenkins user database. production-approvers is a group, which only works if the Security Realm provides groups (LDAP, Active Directory, SSO), as was the case with developers in 05-02. Role-based Strategy roles do not work here: they are not the user's groups. Bear in mind, too, that Jenkins administrators can always respond to an input, and that anyone with Job/Cancel can press Abort.
  • CHANGE_REFERENCE and APPROVED_BY are available as environment variables inside the stage; that is why they are copied to env.APPROVAL, which does persist.
  • If nobody approves within 24 hours, the timeout interrupts the wait and the build ends ABORTED. staging-01 keeps the new version (which passed acceptance) and production is not touched. To deploy it later, run orders-api-cd again with the same version.
  • If someone presses Abort, the result is the same: ABORTED and production untouched.

While it waits, the build appears paused in Stage View and Pipeline Graph View, and in the console:

[Pipeline] stage
[Pipeline] { (Approval)
[Pipeline] timeout
Timeout set to expire in 1 day 0 hr
[Pipeline] input
Deploy the version validated in staging to production?
Deploy to production or Abort

Anyone with permission sees the form by clicking that link, in the build's Paused for Input menu, or at the <build>/input/ URL included in the Slack notice. The linux-agent-01 executor is free for the entire wait: check it in Build Executor Status.

Production

        stage('Deploy to production') {
            agent {
                label 'linux'
            }
            options {
                lock(resource: 'env-production')
                timeout(time: 20, unit: 'MINUTES')
            }
            steps {
                milestone(label: 'Production')
                script { env.CURRENT_ENV = 'production' }
                unstash 'release'
                sshagent(credentials: ['ssh-production']) {
                    sh label: 'Deploy to prod-01 and prod-02, one after the other', script: '''
                        for node in $PRODUCTION_NODES; do
                            sh deploy/deploy.sh "$node"
                        done
                    '''
                }
            }
            post {
                cleanup {
                    cleanWs()
                }
            }
        }
  • for node in $PRODUCTION_NODES: the variable contains prod-01.tecnoshop.local prod-02.tecnoshop.local; without quotes, the shell splits it into two words.
  • The Jenkins sh step runs with -e: if deploy.sh fails on prod-01 (for example, the health check), the loop stops and prod-02 is not touched.
  • Notice what is not there: no load balancer logic. While prod-01 restarts, nginx will keep sending it requests and some will fail (or be retried on prod-02, depending on the load balancer configuration). And if the health check on prod-01 fails, it is left with the new, broken version. Solving both, with progressive deployment and automatic rollback, is the subject of Automating Deployments: Strategies and Rollback.

Coordinating Builds: lock and milestone

Several orders-api-cd builds can coexist: the one for 1.1.0 waiting for approval and the one for 1.1.1, just triggered, deploying to staging. That is why disableConcurrentBuilds() is not used: the second would wait up to 24 hours for the first to be approved. Instead:

Mechanism Where What it guarantees
lock(resource: 'env-staging') Option of the Staging stage Only one deployment + acceptance at a time on staging-01, even if another job tries (the rollback from 07-04, for example)
lock(resource: 'env-production') Option of Deploy to production Only one deployment at a time to production
milestone(label: 'Staging') On entering staging A newer build that reaches staging aborts older ones that had not reached it yet
milestone(label: 'Production') On entering production If 1.1.1 is approved and reaches production, the 1.1.0 build that was still waiting is aborted; and an old version can never be deployed after a new one

Details:

  • The Lockable Resources plugin (the one from 04-01) creates the env-staging and env-production resources automatically the first time they are requested; you can see them, and who holds them, in Manage Jenkins → Lockable Resources.
  • lock as a stage option is acquired before the agent is allocated: a build waiting for the resource does not hold an executor.
  • milestone orders by build number, which in CD matches the order in which builds were triggered. A manual rerun of an old version (to go back to it) is a new build and the milestone lets it through, which is what you want.

Recording and Notification: notifyDeployment in tecnoshop-lib v1.4.0

Why notifyTeam Is Not Enough

notifyTeam from 06-07 decides based on BRANCH_NAME, and in a regular Pipeline job that variable does not exist: the step would say that branch '' does not notify and would never send anything. Besides, its rules (notifying changes of state in a main build) do not match what matters about a deployment: which version reached which environment, and when an approval is needed.

Laura adds a new step to the library. (Exercise 3 in 06-07 sketched a hypothetical v1.4.0 with a deployChannel parameter; it stayed an exercise and was never released. The real v1.4.0 is this one, and it covers that same need with a dedicated step.)

vars/notifyDeployment.groovy:

/**
 * Announces a deployment milestone for a release. For CD pipelines.
 *
 *   notifyDeployment application: 'orders-api', channel: '#ci-orders', environment: 'production',
 *                    version: params.VERSION, result: 'OK', detail: 'Approved by laura'
 *
 * result: OK (default), PENDING, FAILED, CANCELLED or REVERTED.
 * Never changes the build result: if a value is missing or Slack fails, it says so in the console.
 */
def call(Map config = [:]) {
    for (String field : ['application', 'channel', 'environment', 'version']) {
        if (!config[field]) {
            echo "notifyDeployment: missing parameter '${field}'; not notifying"
            return
        }
    }
    Map formats = [
        OK       : [color: 'good',    text: "deployed to ${config.environment}"],
        PENDING  : [color: '#439FE0', text: "ready in ${config.environment}: pending approval for production"],
        FAILED   : [color: 'danger',  text: "deployment failed in ${config.environment}"],
        CANCELLED: [color: '#999999', text: 'did not reach production (canceled or not approved in time)'],
        REVERTED : [color: 'warning', text: "reverted in ${config.environment}: the previous version has been restored"]
    ]
    String result = config.result ?: 'OK'
    Map format = formats[result]
    if (!format) {
        echo "notifyDeployment: unknown result '${result}'; not notifying"
        return
    }

    String link = result == 'PENDING' ? "${env.BUILD_URL}input/" : env.BUILD_URL
    String text = "*${config.application} ${config.version}* ${format.text}" +
                  (config.detail ? "\n${config.detail}" : '') +
                  "\n<${link}|${env.JOB_NAME} #${env.BUILD_NUMBER}>"
    echo "notifyDeployment: ${result} → Slack ${config.channel}"
    try {
        slackSend(channel: config.channel, color: format.color, message: text)
    } catch (Exception e) {
        echo "notifyDeployment: could not notify Slack (${e.message})"
    }
}
  • The validation does not use error: in the post section of a build that failed early (for example, without VERSION), an error in the notification would hide the real reason. The same principle as the try/catch in notifyTeam.
  • formats: the text and color for each result. REVERTED will be used by the rollback in 07-04.
  • PENDING links directly to the approval form (<build>/input/).

It is released with the usual flow (branch, test PR, merge, vars/notifyDeployment.txt, a JenkinsPipelineUnit test) and the v1.4.0 tag: a new, compatible feature. orders-api can stay on v1.3.0 until it needs it; ci/Jenkinsfile.cd starts directly with @Library('[email protected]') _.

Why everything in #ci-orders and not in a deployments channel, as 06-07 suggested for dev? Because these notices are few (one or two per release) and nearly all of them are actionable: something needs approving, or something has failed. If the volume grew, OK would move to its own channel.

The Description and the History

Every CD build describes itself: name #12 · 1.1.0, description orders-api 1.1.0 · approved by laura (CHG-2026-0142: ...) and the jar fingerprint linked to the tag build. The orders-api-cd history is the deployment log for staging and production, which is where the DORA metrics from 07-01 come from.

Optional: An Annotation in Grafana

If you are using the Grafana instance from 05-05, an annotation marks the moment of the deployment on every chart, and makes it obvious whether a change in the metrics coincides with a new version. Create a service account in Grafana with permission to write annotations and store its token as a Secret text credential, grafana-annotations, in the orders-delivery folder. In the post section of the production stage:

            post {
                success {
                    withCredentials([string(credentialsId: 'grafana-annotations', variable: 'GRAFANA_TOKEN')]) {
                        sh label: 'Grafana annotation', script: '''
                            PAYLOAD=$(printf '{"tags":["deployment","orders-api","production"],"text":"orders-api %s in production (build %s)"}' "$APP_VERSION" "$BUILD_NUMBER")
                            curl -sf -X POST http://grafana:3000/api/annotations \
                                 -H "Authorization: Bearer $GRAFANA_TOKEN" -H 'Content-Type: application/json' \
                                 -d "$PAYLOAD" || echo "WARNING: could not create the annotation in Grafana"
                        '''
                    }
                }
            }
  • printf builds the JSON in the shell, with the version and build number as arguments: no hand-escaped quotes and no Groovy interpolation.
  • || echo: a failed annotation must not make a successful deployment fail.

Who Triggers and Who Approves

With the roles from 05-02, without changing their configuration:

Who Role On orders-delivery/orders-api-cd
A tag build System identity Triggers it with VERSION and SHA256
diego orders-developer (orders-.*) View, trigger (for example, to redeploy a version to staging) and cancel
marta qa ((orders|catalog)-.*) View and trigger
laura admin Everything, including approval (she is in submitter and is also an administrator)
The production-approvers group (from the corporate directory) Approve the input
  • Triggering CD does not grant access to production: the build stops at Approval and only continues if someone in submitter approves.
  • Nobody except administrators has Job/Configure or Run/Replay on this job. That matters: Replay would allow a modified Jenkinsfile.cd to run, unreviewed, with access to ssh-production.
  • Jenkinsfile.cd and the scripts are read from orders-api's main: whoever can merge into main can change the deployment process. The protect-main rule requires a review; in 07-05 you will add the requirement that changes to ci/ and deploy/ are always approved by the platform team.
  • Do not add preserveStashes() to this pipeline: with stashes preserved, someone with Job/Build could use Restart from Stage from Deploy to production and skip the approval. Without them, that stage cannot find the release stash and fails.

The Complete ci/Jenkinsfile.cd

@Library('[email protected]') _

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        = 'http://nexus:8081'
        STAGING_SERVER   = 'staging-01.tecnoshop.local'
        PRODUCTION_NODES = 'prod-01.tecnoshop.local prod-02.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
                sh label: 'Download from Nexus and verify', script: 'sh deploy/fetch-release.sh "$APP_VERSION"'
                fingerprint 'target/orders-api-*.jar'
                stash name: 'release', includes: 'target/orders-api-*.jar,deploy/**,ci/**'
            }
            post {
                cleanup {
                    cleanWs()
                }
            }
        }

        stage('Staging') {
            agent {
                label 'linux'
            }
            options {
                lock(resource: 'env-staging')
                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-01 over SSH', script: 'sh deploy/deploy.sh "$STAGING_SERVER"'
                        }
                    }
                }
                stage('Acceptance tests') {
                    steps {
                        sh label: 'QA acceptance criteria',
                           script: 'sh ci/acceptance.sh "http://$STAGING_SERVER:8081" "$APP_VERSION" staging'
                        notifyDeployment application: 'orders-api', channel: '#ci-orders', environment: 'staging',
                                         version: params.VERSION, result: 'PENDING'
                    }
                }
            }
            post {
                cleanup {
                    cleanWs()
                }
            }
        }

        stage('Approval') {
            options {
                timeout(time: 24, unit: 'HOURS')
            }
            input {
                message 'Deploy the version validated in staging to production?'
                ok 'Deploy to production'
                submitter 'laura,production-approvers'
                submitterParameter 'APPROVED_BY'
                parameters {
                    string(name: 'CHANGE_REFERENCE', defaultValue: '',
                           description: 'Reference of the approved change and a short reason (e.g. CHG-2026-0142: filter orders by status)')
                }
            }
            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 = "orders-api ${params.VERSION} · approved by ${env.APPROVAL}"
                }
            }
        }

        stage('Deploy to production') {
            agent {
                label 'linux'
            }
            options {
                lock(resource: 'env-production')
                timeout(time: 20, unit: 'MINUTES')
            }
            steps {
                milestone(label: 'Production')
                script { env.CURRENT_ENV = 'production' }
                unstash 'release'
                sshagent(credentials: ['ssh-production']) {
                    sh label: 'Deploy to prod-01 and prod-02, one after the other', script: '''
                        for node in $PRODUCTION_NODES; do
                            sh deploy/deploy.sh "$node"
                        done
                    '''
                }
            }
            post {
                cleanup {
                    cleanWs()
                }
            }
        }
    }

    post {
        success {
            notifyDeployment application: 'orders-api', channel: '#ci-orders', environment: 'production',
                             version: params.VERSION, detail: "Approved by ${env.APPROVAL}"
        }
        failure {
            notifyDeployment application: 'orders-api', channel: '#ci-orders',
                             environment: env.CURRENT_ENV ?: 'preparation', version: params.VERSION, result: 'FAILED'
        }
        aborted {
            notifyDeployment application: 'orders-api', channel: '#ci-orders', environment: 'production',
                             version: params.VERSION, result: 'CANCELLED'
        }
    }
}

What is worth highlighting about the whole thing:

  • No global timeout: the pipeline can last up to 24 hours because of the approval; each stage with an agent has its own short timeout.
  • buildDiscarder(logRotator(numToKeepStr: '100')): the CD history is the deployment log, so more builds are kept than in CI. There are no archived artifacts to limit: the artifact is in Nexus.
  • NEXUS_URL = 'http://nexus:8081': the lab address; at TecnoShop, https://nexus.tecnoshop.local.
  • APP_VERSION and DEPLOY_VERSION: the variables that deploy.sh and fetch-release.sh expect, derived from the parameter. The scripts read them from the shell; they are never interpolated with Groovy in an sh step.
  • The global post section has no agent: notifyDeployment only uses slackSend and echo.

The First Release Through the Chain

With Jenkinsfile.cd, deploy/fetch-release.sh, ci/acceptance.sh, the deploy.sh change and the extended known_hosts merged into main (through a PR, as always), Diego publishes 1.1.0 following the process from 06-05: a release/1.1.0 branch, versions:set to 1.1.0, the v1.1.0 tag, versions:set to 1.2.0-SNAPSHOT, a PR with a merge commit, git push origin v1.1.0 and Build Now in the Tags tab of orders-api.

What you will see:

  1. The v1.1.0 build ends green with the description orders-api 1.1.0 (v1.1.0) → orders-api-cd.
  2. Build #2 · 1.1.0 appears in orders-delivery/orders-api-cd (#1 was the failed validation). It downloads, verifies, deploys to staging-01 and passes all seven criteria.
  3. The blue "ready in staging: pending approval" notice arrives in #ci-orders.
  4. Laura opens the link, types in the change reference and presses Deploy to production.
  5. The build deploys to prod-01 and prod-02 and posts a green notice.

Check the result from the agent: curl -s http://prod-02.tecnoshop.local:8081/actuator/info should return version 1.1.0 and the production environment.

If you would rather have tags built automatically when they are pushed, the Basic Branch Build Strategies plugin adds a build strategy for tags to the multibranch job (with an age limit so that it does not build every historical tag). When you configure strategies, you also have to add the branch and PR strategies explicitly, because the default ones stop applying. For now, TecnoShop keeps Build Now as an explicit act of publishing.

Common Mistakes and Tips

  • No item named /orders-delivery/orders-api-cd found in the tag build: the job does not exist, it is in another folder, or the path was written without a leading slash.
  • ERROR: Could not find credentials entry with ID 'ssh-production': the credential is in another folder or the job is outside orders-delivery. That is exactly the isolation you were after; check the location.
  • The input does not show the button to the person who should approve: their user is not in submitter, or the Security Realm does not provide the group. With Jenkins' own user database, only user IDs work.
  • input inside the steps of a stage with an agent: it holds an executor for up to 24 hours.
  • curl: (22) The requested URL returned error: 404 when downloading: the version is not published in maven-releases (perhaps it was triggered by hand with a version that only exists as a tag, or the tag build failed in Publish).
  • sha256sum: WARNING: 1 computed checksum did NOT match: the jar in Nexus is not the one CI tested. Do not deploy it: investigate who could have changed that artifact, and how.
  • Acceptance fails on A2 with the correct version deployed: the jar was built before build-info was added in 07-02, or the server does not expose info. Earlier releases (1.0.0) will not pass A2: that is expected.
  • Approving without a change reference: the build fails at Approval and has to be run again (staging will be redeployed with the same version, with no side effects). Type in the reference before pressing the button.
  • Tip: before approving, open the acceptance results and the version's changelog (the diff between tags in GitHub). The approval decides when and what; the tests have already said whether it works.

Exercises

Exercise 1. Set up the three servers, the folder, the credentials and the job, and take 1.1.0 all the way to production. Then trigger orders-api-cd by hand with VERSION=1.1.0-SNAPSHOT, then with VERSION=9.9.9, and finally with VERSION=1.1.0 and a made-up 64-character SHA256. State the stage where each one fails and the message it fails with.

Exercise 2. Trigger two orders-api-cd builds: the first with 1.1.0 and, while it waits for approval, the second one also with 1.1.0 (simulating a second release). Approve the second one first and then try to approve the first. What happens, and why? What role does each lock and each milestone play?

Exercise 3. Marta wants the person who approves production not to be the same person who triggered CD (separation of duties). Propose how to check this in the Approval stage. Hint: currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause') returns a list of maps with the userId key of whoever triggered the build by hand (empty if another job triggered it).

Solutions

Solution 1. With 1.1.0-SNAPSHOT, it fails in Validate parameters: VERSION must have the form X.Y.Z (e.g. 1.1.0); received '1.1.0-SNAPSHOT'; no agent is allocated. With 9.9.9, it passes validation and fails in Fetch release with curl: (22) The requested URL returned error: 404, because that version does not exist in maven-releases. With the made-up SHA-256, the download and the Nexus SHA-1 checksum are fine, but sha256sum -c responds target/orders-api-1.1.0.jar: FAILED and WARNING: 1 computed checksum did NOT match; the build fails before touching staging. In all three cases a FAILED notice for preparation reaches Slack, because CURRENT_ENV had not been set yet (the first one will read "orders-api 1.1.0-SNAPSHOT deployment failed in preparation", which is exactly what happened). None of them got as far as touching a server.

Solution 2. The first build (#A) deploys to staging, passes acceptance, releases env-staging and waits at Approval. The second one (#B) passes milestone('Staging') (the first one had already passed it, so nothing is aborted), takes env-staging, deploys, passes acceptance and waits too. When you approve #B, it passes milestone('Production'), takes env-production and deploys. At that very moment, Jenkins aborts #A: it is older, it had passed the previous milestone (Staging) but not this one. When you go to approve it, the form will be gone: its console will show a message saying it was canceled by a newer build, and the CANCELLED notice will arrive in Slack. Result: production has the version from the newest build and never goes backward because of an unfortunate approval order. The locks guarantee that deployments (and the staging acceptance tests) do not overlap; the milestones, that the final order is the order of the builds.

Solution 3. In the steps of Approval, before accepting the approval:

script {
    def launchers = currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause').collect { it.userId }
    if (launchers.contains(env.APPROVED_BY)) {
        error "Separation of duties: ${env.APPROVED_BY} triggered this deployment and cannot approve it"
    }
}

getBuildCauses with the UserIdCause class returns the "started by user X" causes; collect { it.userId } extracts the IDs. If a tag build triggered CD, the list is empty and anyone in submitter can approve. For the rule to be complete, the trigger from the tag should also record who pushed the tag (for example, in an additional parameter), because that person is, in practice, the one requesting the deployment. Bear in mind that administrators can respond to the input even if they are not in submitter, but this check would apply to them too.

Conclusion

orders-api now has an end-to-end continuous delivery pipeline. orders-api-cd, a Pipeline job inside the orders-delivery folder that reads ci/Jenkinsfile.cd from main, receives a version (validated with ==~) and the SHA-256 from the tag build, downloads exactly that jar from Nexus with deploy/fetch-release.sh and verifies both its Nexus checksum and the CI one: build once, deploy many times, with hard evidence. It deploys it to staging-01 with ssh-staging, runs Marta's acceptance criteria in ci/acceptance.sh (health, version, environment configuration, listing, filter, 200 and 404), waits for approval from laura or the production-approvers group with the input directive in a stage with no agent, a global agent none and a 24-hour timeout, and deploys to prod-01 and prod-02 with ssh-production. The staging and production credentials live in the folder and only this pipeline can use them; the per-environment configuration is in /etc/orders-api/ thanks to the Spring profile and SPRING_CONFIG_ADDITIONAL_LOCATION; lock and milestone coordinate simultaneous builds; and notifyDeployment, new in tecnoshop-lib v1.4.0, together with each build's name and description, turns the history into a deployment log. One weak spot remains in plain sight: the two production servers are updated one after the other without taking them out of the load balancer, and if the new version does not start, they are left broken. In Automating Deployments: Strategies and Rollback you will learn the strategies for deploying without interrupting the service, and how to roll back, both automatically and by hand.

© Copyright 2026. All rights reserved