Throughout this module you have added nested and parallel stages, stashes, environment variables, credentials, multibranch and a shared library to orders-api. You have all the pieces; what separates a pipeline that works today from one the team will still be able to maintain two years from now is how they are combined. In this lesson you will gather the judgment you have been building into a set of best practices for a Jenkinsfile: where the logic should live, how to order and bound stages, how to make builds reproducible and secure, when to use script, what durability implies and why a manual wait must not block an executor. You will apply them in a code review of a problematic Jenkinsfile from another TecnoShop team, move the orders-api Smoke stage into the library and finish with the Jenkinsfile that closes module 4 and a checklist for your own pipelines.

Scope: Pipeline Practices vs. Instance Practices

This lesson deals with what is decided in the Jenkinsfile and in the shared library: what each team controls. Installation practices (how many executors the controller has, how folders and permissions are organized, backups, plugin upgrades, monitoring) are the platform team's responsibility and are covered in module 5 and in Jenkins Best Practices.

Build Logic Lives in the Tools, Not in Groovy

Jenkins orchestrates: it decides what runs, where, in what order and what is done with the result. Building is the job of Maven, npm, Gradle or the repository's scripts.

Logic in Groovy (avoid it) Logic in the tool (prefer it)
A loop in script that walks through modules and calls sh for each one A multi-module Maven project: ./mvnw package
Computing the version number with string manipulation ./mvnw help:evaluate or the pom.xml itself
Copying files to dist/ with Jenkins steps npm run build (as in catalog-web)
Starting the application and polling it with waitUntil A versioned shell script (like the Smoke stage)

Advantages: developers can reproduce the build on their own machine with the same command, build tools have their own tests and documentation, and the pipeline stays readable. A simple test: if you have to read the Jenkinsfile to find out how your project is built, it contains too much logic.

Minimal Groovy: the Controller Is Not a Build Machine

All the Groovy in a pipeline (conditions, loops, string manipulation, reading files with readFile and processing them) runs on the controller, not on the agent, and it also goes through the CPS transformation you saw in 03-02, which frequently saves the program's state to disk. Consequences:

  • Processing a large file with Groovy (for example, reading an XML report line by line to count failures) consumes CPU and memory on the controller, which all the builds in the installation share.
  • CPS code is much slower than regular Groovy and has restrictions (non-serializable objects, @NonCPS...).

Rules:

  • If you need to process data, do it with a command on the agent (sh, jq, a script) or with a plugin step designed for it (for example, junit for test reports, in 06-03).
  • Do not overuse script { }. A block of two or three lines to compute a value is reasonable; if it grows, or is repeated across several projects, it goes into a library step, as you did with infoBuild in 04-06. The orders-api Jenkinsfile no longer has a single script block.

Fail Fast: the Order of the Stages

The goal of a pipeline is to give fast feedback, especially when something goes wrong. Order the stages from cheapest and most likely to fail to most expensive:

flowchart LR
    A["Build<br/>seconds"] --> B["Unit tests +<br/>analysis (parallel)"]
    B --> C["Package"]
    C --> D["Smoke<br/>starts the app"]
    D --> E["Deployment<br/>(main only)"]
  • A compilation error is caught in seconds, without waiting for tests or packaging.
  • Independent work goes in parallel with failFast, as in 04-02: if the tests fail, the analysis is aborted.
  • Slow checks (integration, performance, security) come after the fast ones, and those that depend on external environments come last.
  • Validate up front anything that could invalidate the whole build (inconsistent parameters), with error and a clear message.

Timeouts on Anything That Can Hang

A hung build holds an executor indefinitely and blocks everything waiting in the queue.

Level How In orders-api
Pipeline options { timeout(...) } 20 minutes
Stage options { timeout(...) } in the stage Tests (10), Analysis (5), Smoke (3)
Block timeout(...) { } as a step Around waitUntil, retry or waits for external services

Each timeout should be generous but realistic: roughly two or three times the normal duration. A timeout that is too tight causes false failures; one of 24 hours protects against nothing.

Reproducible and Idempotent Builds

Reproducible: the same commit produces the same result today, tomorrow and on any agent. Idempotent: repeating a build (or a stage) does not cause different or cumulative effects.

Practice At TecnoShop
Tool versions pinned in the repository Maven Wrapper (./mvnw) in orders-api
Exact dependencies package-lock.json + npm ci in catalog-web (never npm install in CI)
Jenkins tools with stable names The node-18, node-20 and node-22 installations
Pinned shared library version @Library('[email protected]')
A clean workspace in every build cleanWs() in cleanup and Maven's clean
No dependency on the state of earlier builds Each stage requests its files with unstash
Docker images with a fixed tag, never latest You will apply this in 08-01
Deployments that can be repeated without breaking anything You will work on this in 07-04

Parameters with Safe Default Values

Automatic builds (multibranch scans, cron, webhooks) always use the default values. Design parameters with that case in mind:

  • The default value must be the safest one: RUN_TESTS=true, ENVIRONMENT=dev. Never production as the first option of a choice.
  • A dangerous action is enabled with a boolean that defaults to false, and its name says so (FORCE_DEPLOY, not MODE).
  • Write a description that explains when to change it.
  • Safety conditions do not depend on parameters alone: Deploy to dev also requires branch 'main', so no PR can deploy even if someone changes the parameters.

Secrets Out of the Log and Out of Interpolation

You learned this in 04-04; as pipeline practice it boils down to this:

  • No secrets in the Jenkinsfile, in plain-text environment values or in text parameters.
  • withCredentials (or credentials() in a stage's environment) around the steps that need them, not around the whole pipeline.
  • In sh, single quotes and shell variables. If you see the A secret was passed to "sh" using Groovy String interpolation warning, treat it as an error.
  • External data (branch names, PR titles, free-text parameters) is not interpolated with Groovy in sh either.
  • Secrets only on the branches that need them (when { branch 'main' }).

Agents, Workspaces and Stashes

  • A global agent none and per-stage agents once there are agents: this is how each stage runs where it belongs without holding executors during waits. orders-api keeps agent any while only the built-in node exists; when you migrate in 05-01, remember that the APP_VERSION sh in the global environment needs an agent, as we noted in 04-03.
  • Never build on the controller in production: the current agent any is a concession to the lab environment.
  • Clean workspaces: cleanWs() in cleanup; temporary subdirectories with dir(...) { deleteDir() }.
  • Minimal stash: only what the next stage needs (target/*.jar, not target/**), and no dependency directories. For large files, an artifact repository.
  • Self-sufficient stages: every stage that can be rerun with Restart from Stage retrieves what it needs.

Clear, Stable Stage Names

Stage names appear in Stage View, in Pipeline Graph View, in Restart from Stage, in notifications and in duration metrics. TecnoShop's conventions:

  • In English, short and descriptive: Build, Tests, Package, Smoke, Deploy to dev.
  • Stable: no variable data. A stage("Build ${BUILD_NUMBER}") creates a "different" stage in every build, breaks Stage View (each build gets its own columns) and makes it impossible to compare durations.
  • Consistent across projects: the same words for the same things (Tests, not Test in one project and Unit tests in another).
  • Unique within the pipeline: Jenkins rejects two stages with the same name.

A Short Jenkinsfile Backed by the Library: smokeSpringBoot

The Smoke stage is the last large block in the orders-api Jenkinsfile, and its logic (starting a Spring Boot jar and checking /actuator/health) works for any TecnoShop Java service. Laura moves it into the library in a new version, following the workflow from 04-06.

resources/com/tecnoshop/ci/smoke-spring-boot.sh:

#!/bin/sh
set -eu
JAR=$(ls target/*.jar)
PORT=$((BASE_PORT + EXECUTOR_NUMBER))
java -jar "$JAR" --server.port="$PORT" > smoke.log 2>&1 &
PID=$!
trap 'kill $PID 2>/dev/null || true' EXIT
i=1
while [ "$i" -le 30 ]; do
    if curl -sf "http://localhost:$PORT/actuator/health" | grep -q '"status":"UP"'; then
        echo "Smoke OK: the application is responding on port $PORT (attempt $i)"
        if [ -n "$EXTRA_PATH" ]; then
            curl -sf "http://localhost:$PORT$EXTRA_PATH" | grep -q "$EXPECTED_TEXT"
            echo "Smoke OK: $EXTRA_PATH contains '$EXPECTED_TEXT'"
        fi
        exit 0
    fi
    i=$((i + 1))
    sleep 2
done
echo "ERROR: the application did not start within 60 seconds"
cat smoke.log
exit 1
  • It is the same script as in 04-01, now as a versioned, generic file: the extra path and the expected text arrive through environment variables.
  • set -eu: -e exits on any error and -u treats using an undefined variable as an error, which catches typos in names.

vars/smokeSpringBoot.groovy:

/**
 * Smoke check for a Spring Boot service packaged as a jar and saved in a stash.
 *
 *   smokeSpringBoot extraPath: '/api/orders', expectedText: 'SHIPPED'
 */
def call(Map config = [:]) {
    String stashName = config.stash ?: 'jar'
    String basePort = (config.basePort ?: 18090).toString()

    dir('smoke') {
        deleteDir()
        unstash stashName
        writeFile file: 'smoke.sh', text: libraryResource('com/tecnoshop/ci/smoke-spring-boot.sh')
        withEnv(["BASE_PORT=${basePort}",
                 "EXTRA_PATH=${config.extraPath ?: ''}",
                 "EXPECTED_TEXT=${config.expectedText ?: ''}"]) {
            sh label: 'Start the jar and check that it responds', script: 'sh smoke.sh'
        }
    }
}
  • libraryResource + writeFile: brings the library script into the workspace.
  • withEnv: the parameters reach the script as environment variables, not interpolated into the shell code. That keeps the step safe even if someone passes it text with special characters.
  • With its vars/smokeSpringBoot.txt and a JenkinsPipelineUnit test, it is released as v1.1.0: it is a new, compatible feature. catalog-web can stay on v1.0.0.

In orders-api, the stage goes from 30 lines to this:

        stage('Smoke') {
            options {
                timeout(time: 3, unit: 'MINUTES')
            }
            steps {
                smokeSpringBoot extraPath: '/api/orders', expectedText: 'SHIPPED'
            }
        }

The goal is not the shortest possible Jenkinsfile, but one that can be read at a glance: what each stage does stays in the Jenkinsfile; how it does it lives in the library and in the tools.

Quality of the Jenkinsfile Itself: Linting and PR Review

The Jenkinsfile is production code. Treat it as such:

  • Validate it with the linter before every commit, from the editor or with the pre-commit hook from 03-06.
  • Change the pipeline on a branch and through a PR: the multibranch job builds the PR with the new Jenkinsfile before it reaches main, as you did in 04-05.
  • Review it like any other code, paying special attention to credentials, deployment conditions and default values. The review in section 16 is an example.
  • Test the library with JenkinsPipelineUnit and its own multibranch job.

Durability: durabilityHint

To survive a controller restart, Jenkins saves the state of each pipeline to disk very frequently. That writing has a cost: in installations with many builds, it can become a bottleneck on the controller's disk. The durabilityHint option lets you adjust that trade-off:

options {
    durabilityHint('PERFORMANCE_OPTIMIZED')
}
Value Disk writes If the controller goes down abruptly...
MAX_SURVIVABILITY (the default) Maximum The pipeline resumes where it was
SURVIVABLE_NONATOMIC Fewer, with no atomicity guarantee It usually resumes; it may lose the last step
PERFORMANCE_OPTIMIZED Minimum The pipeline cannot resume: it is lost and must be rerun; the log may be incomplete

With PERFORMANCE_OPTIMIZED, an orderly Jenkins restart does preserve the state; the risk is an unexpected crash. It is reasonable for short builds that can be repeated without consequences (PRs, for example) and not for pipelines that deploy or wait for approvals. TecnoShop does not use it in orders-api for now: its builds are short and its main branch deploys. The default for the whole installation is set in Manage Jenkins → System, in the pipeline speed and durability section, and you will come back to its effect on performance in Optimizing Jenkins Performance.

Manual Waits Without Blocking Executors

A manual approval (input) can take hours. If the wait happens inside a stage that has an agent assigned, the build holds an executor the whole time while doing nothing; with the built-in node's two executors, two pending approvals would bring all of TecnoShop's builds to a halt.

// ANTI-PATTERN: the executor stays blocked while waiting
stage('Approve') {
    steps {
        input 'Deploy to staging?'
    }
}

The rules, which you will apply when designing promotion between environments in Setting Up a CD Pipeline:

  • Wait without an agent: the stage-level input directive (not the step inside steps) with agent none on the pipeline, so that no executor is reserved until someone approves.
  • Always with a timeout: an approval nobody attends to must expire.
  • Never inside a lock or any block that holds resources while waiting.

Anti-Pattern Table

Anti-pattern Problem Alternative
Secrets written in the Jenkinsfile Leaked in Git and in the log Credentials + withCredentials
sh "...${SECRET}..." or interpolated external data Exposed secrets and command injection Single quotes and shell variables
mvn or npm install in CI Uncontrolled versions ./mvnw, npm ci with a lockfile
Build logic in script loops Unreadable, slow and running on the controller Build tool or versioned script
Processing large files with Groovy Controller CPU and memory Commands on the agent or plugin steps
Pipeline without timeout Executors blocked indefinitely timeout on the pipeline, stages and waits
Dangerous default values Automatic builds that deploy to production or skip tests Safe default values
Dynamic stage names Useless Stage View, no comparisons Fixed names
input inside steps with an agent Executor held for hours input directive without an agent + timeout
if (params.X == 'false') Compares a boolean with text: never true if (!params.X)
Copying and pasting blocks between Jenkinsfiles Divergence and multiple maintenance Shared library steps
@Library without a version in stable projects Other people's changes break the build without warning A version pinned to a tag
Stashing entire directories Overloaded controller Only the necessary files
Deployments without a branch condition Any branch or PR deploys when { branch 'main' }
Workspace never cleaned Builds that depend on leftovers, full disk cleanWs() in cleanup

Code Review: the shipments-api Jenkinsfile

TecnoShop's logistics team has started a new service, shipments-api, and asks Laura to review its Jenkinsfile before creating the multibranch job. It is a fictitious example, but every problem in it is real and common:

pipeline {
    agent any
    environment {
        NEXUS_PASS = 'F4k3-S3cr3t-123'
    }
    parameters {
        booleanParam(name: 'SKIP_TESTS', defaultValue: true, description: '')
        choice(name: 'TARGET', choices: ['production', 'staging', 'dev'])
    }
    stages {
        stage("Build ${BUILD_NUMBER}") {
            steps {
                sh 'mvn clean install'
            }
        }
        stage('Test') {
            steps {
                script {
                    if (params.SKIP_TESTS == 'false') {
                        sh 'mvn test'
                    }
                    def xml = readFile('target/surefire-reports/TEST-com.tecnoshop.shipments.ShipmentTest.xml')
                    def failures = 0
                    for (line in xml.split('\n')) {
                        if (line.contains('<failure')) { failures++ }
                    }
                    echo "Failures: ${failures}"
                }
            }
        }
        stage('Deploy') {
            steps {
                input 'Deploy?'
                sh "curl -u admin:${NEXUS_PASS} --upload-file target/shipments-api.jar http://nexus.tecnoshop.local/repository/shipments/"
                sh "echo Deployed to ${params.TARGET} from ${env.GIT_BRANCH}"
            }
        }
    }
}

Laura's comments on the PR:

# Line Problem Fix
1 NEXUS_PASS = '...' Plain-text secret in the repository nexus-deployer credential with withCredentials; revoke the exposed password
2 SKIP_TESTS defaults to true Automatic builds test nothing RUN_TESTS with defaultValue: true
3 choices: ['production', ...] The default value is production dev first; production only in the CD pipeline
4 description: '' and no description Nobody knows when to change them Useful descriptions
5 stage("Build ${BUILD_NUMBER}") Dynamic name: breaks Stage View Build
6 mvn Uncontrolled Maven version ./mvnw (via mavenTecnoShop)
7 clean install install already runs the tests and installs the jar into the node's shared ~/.m2 clean compile, then test and package
8 params.SKIP_TESTS == 'false' A boolean compared with text: never true when { expression { params.RUN_TESTS } }
9 Loop over the XML Processes reports on the controller with Groovy The junit step (06-03)
10 input in steps Blocks an executor and has no timeout Out of this pipeline; approvals belong in the CD pipeline (07-03)
11 sh "...${NEXUS_PASS}..." Secret interpolated by Groovy Single quotes with withCredentials variables
12 http:// Credentials over an unencrypted channel https://
13 ${env.GIT_BRANCH} interpolated in sh External data in the shell; it also carries origin/ Groovy echo with BRANCH_NAME
14 Deploy without when Any branch or PR publishes when { branch 'main' }
15 No options No timeout, no retention, no timestamps Standard options
16 No post Workspace never cleaned cleanup { cleanWs() }
17 Test, Deploy Names that differ from the rest of TecnoShop (Test instead of Tests; Deploy for a stage that actually publishes) Tests, Publish to Nexus

The corrected version, backed by the library:

@Library('[email protected]') _

pipeline {
    agent any

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

    parameters {
        booleanParam(name: 'RUN_TESTS', defaultValue: true,
                     description: 'Uncheck only to quickly verify that it compiles. Nothing is published without tests.')
    }

    environment {
        MAVEN_ARGS = '-B -ntp'
    }

    stages {
        stage('Build') {
            steps {
                echo "Build ${env.BUILD_NUMBER} of ${env.JOB_NAME} | branch ${env.BRANCH_NAME} | RUN_TESTS=${params.RUN_TESTS}"
                mavenTecnoShop 'clean compile'
            }
        }
        stage('Tests') {
            when {
                expression { params.RUN_TESTS }
            }
            options {
                timeout(time: 10, unit: 'MINUTES')
            }
            steps {
                mavenTecnoShop 'test'
            }
        }
        stage('Package') {
            steps {
                mavenTecnoShop '-DskipTests package'
                archiveArtifacts artifacts: 'target/*.jar', fingerprint: true
            }
        }
        stage('Publish to Nexus') {
            when {
                allOf {
                    branch 'main'
                    expression { params.RUN_TESTS }
                }
            }
            options {
                timeout(time: 5, unit: 'MINUTES')
            }
            steps {
                withCredentials([usernamePassword(credentialsId: 'nexus-deployer',
                                                  usernameVariable: 'NEXUS_USER',
                                                  passwordVariable: 'NEXUS_PASSWORD')]) {
                    sh 'curl -sf -u "$NEXUS_USER:$NEXUS_PASSWORD" --upload-file target/shipments-api.jar https://nexus.tecnoshop.local/repository/shipments/'
                }
            }
        }
    }

    post {
        cleanup {
            cleanWs()
        }
    }
}
  • The TARGET parameter goes away: this pipeline builds and publishes; deploying to environments (with their approvals) will be the job of the CD pipeline in module 7.
  • Publishing to Nexus with curl is temporary: in Artifact and Image Repositories you will see the idiomatic way with Maven and, as we noted in 04-04, without passing the password as a process argument.
  • The failure count goes away: the junit step will do it better in 06-03.

Pipeline Checklist

Print this list and go through it every time you write or review a Jenkinsfile:

Structure

  • [ ] Stages have short names, in English, stable and consistent with the other projects.
  • [ ] The order goes from cheapest to most expensive; independent work runs in parallel with failFast.
  • [ ] Parallel branches do not write to the same files.
  • [ ] There are no script blocks longer than a few lines; shared logic is in the library.
  • [ ] The library is loaded with @Library and a pinned version.

Robustness

  • [ ] timeout on the pipeline, on stages that can hang and around waits.
  • [ ] Tools with pinned versions (./mvnw, npm ci with a lockfile, installations with stable names).
  • [ ] Every rerunnable stage retrieves its files with unstash; stashes are small.
  • [ ] cleanWs() in cleanup.
  • [ ] Build and artifact retention with buildDiscarder.

Security

  • [ ] No secrets in the code, in plain-text environment values or in parameters.
  • [ ] Credentials with the smallest scope (withCredentials or a stage's environment).
  • [ ] In sh, single quotes for secrets and external data; no interpolation warnings in the console.
  • [ ] Stages that deploy or use sensitive secrets have when { branch 'main' }.
  • [ ] Parameter default values are the safe ones.

Operations

  • [ ] Manual waits do not hold executors, and they expire.
  • [ ] The console shows the context at the start (branch, version, parameters).
  • [ ] The Jenkinsfile passes the linter, and changes arrive through PRs with a green build.
  • [ ] durabilityHint is only relaxed deliberately, and never in pipelines that deploy.

The orders-api Jenkinsfile at the End of Module 4

This is the complete state in which orders-api finishes the module, after upgrading the library to v1.1.0 and using smokeSpringBoot:

@Library('[email protected]') _

pipeline {
    agent any   // Temporary: in 05-01 the stages will move to an agent with the 'linux' label

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

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

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

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

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

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

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

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

        stage('Smoke') {
            options {
                timeout(time: 3, unit: 'MINUTES')
            }
            steps {
                smokeSpringBoot extraPath: '/api/orders', expectedText: 'SHIPPED'
            }
        }

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

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

A summary of how it evolved over the module:

Lesson What it contributed
04-01 preserveStashes, build-info.txt, stash/unstash of the jar, Smoke stage
04-02 Parallel Checks stage with failFast
04-03 MAVEN_ARGS, IMAGE, APP_VERSION, IMAGE_TAG
04-04 Private repository with github-tecnoshop (no changes to the file)
04-05 Multibranch: cron only on main, no pollSCM, deployment only from main, PR info stage
04-06 tecnoshop-lib: mavenTecnoShop, infoBuild; no script blocks
04-07 smokeSpringBoot and library v1.1.0

Make the change on a branch, open it as a PR, check that the PR build is green and merge it.

Common Mistakes and Tips

  • Applying every practice at once to a pipeline that works: better one at a time, each in its own PR and with its own green build.
  • Confusing "short" with "good": a two-line Jenkinsfile that hides everything in a template can be harder to maintain than a readable 80-line one.
  • Relaxing durabilityHint to "gain speed" without measuring: in small installations it is barely noticeable, and it adds risk.
  • Copying another team's Jenkinsfile without reviewing it: you inherit its mistakes (like those in shipments-api).
  • Forgetting that automatic builds use the default values: that is where a dangerous default does its damage.
  • Tip: keep the checklist in the library repository (for example, in its README.md) and link to it from the PR template in TecnoShop's repositories.

Exercises

Exercise 1. Apply the checklist to the catalog-web Jenkinsfile as it stood at the end of 04-06. List the items it meets and those it does not, and propose the changes.

Exercise 2. A colleague proposes adding durabilityHint('PERFORMANCE_OPTIMIZED') to orders-api "because builds are faster". Write the review comment with your reasoned decision.

Exercise 3. Find the five problems in this snippet and rewrite it:

stage("Deploy ${params.ENVIRONMENT}") {
    steps {
        input 'Approve deployment'
        script {
            for (server in ['srv1', 'srv2', 'srv3']) {
                sh "scp target/*.jar deploy@${server}:/opt/app/ && echo OK on ${server} branch ${env.CHANGE_BRANCH}"
            }
        }
    }
}

Solutions

Solution 1. It meets: stage names in English and stable; a matrix with an agent per cell, so the cells do not write to the same workspace; npm ci with a lockfile; Node installations with stable names; timestamps(), a global timeout and buildDiscarder; cleanWs() in each workspace; a pinned library version (v1.0.0); no secrets. Room for improvement:

  1. There is no timeout on each cell's Test stage: a hung test would use up the global 20-minute timeout with both executors occupied. Add options { timeout(time: 5, unit: 'MINUTES') } to Test.
  2. The console does not show the context at the start (branch and version). Add an echo at the beginning of Build, or in a lightweight initial stage.
  3. The script block in Build that reads the version is acceptable given its size, but if more Node projects arrive, it will deserve a library step.
  4. It does not have disableConcurrentBuilds(): with only two executors, two consecutive builds of the same branch would compete for them with six cells. It is worth adding.

The lesson of the exercise is to go through the list item by item, instead of taking it for granted that something "must surely be there".

Solution 2. Proposed comment: "I would not add it. PERFORMANCE_OPTIMIZED reduces disk writes on the controller, but if Jenkins goes down abruptly, the builds in progress cannot resume and are lost. orders-api builds take about two minutes, so the gain would be minimal, and the main branch deploys to dev: we do not want half-finished deployment builds after a crash. Besides, we have not measured that durability is a bottleneck. If it ever is, we would consider adjusting it in the global configuration for specific workloads, as we will see in 09-03, after measuring."

Solution 3. Problems: (1) a dynamic stage name; (2) input inside steps, which blocks an executor and has no timeout; (3) a deployment logic loop in Groovy (script), which should be in a versioned script or in the deployment tool; (4) CHANGE_BRANCH (external data) interpolated with Groovy in sh, with a risk of injection (and, besides, it only exists in PRs, which should never deploy); (5) there is no when { branch 'main' } condition, and no SSH credential (ssh-staging) for the connection. A reasonable version, pending the CD pipeline in module 7:

stage('Deploy') {
    when {
        branch 'main'
    }
    options {
        timeout(time: 10, unit: 'MINUTES')
    }
    steps {
        withCredentials([sshUserPrivateKey(credentialsId: 'ssh-staging', keyFileVariable: 'SSH_KEY', usernameVariable: 'SSH_USER')]) {
            sh './scripts/deploy.sh "$ENVIRONMENT"'
        }
    }
}

The repository's scripts/deploy.sh script contains the loop over the servers and uses $SSH_KEY and $SSH_USER; the environment arrives as a quoted argument from a shell variable. The manual approval will be designed without blocking executors in 07-03, and SSH deployment with its plugin in 06-06.

Conclusion

With this lesson you close module 4 with judgment as well as technique: build logic lives in the tools and in versioned scripts, Groovy is kept to a minimum because it runs on the controller, stages are ordered to fail fast and all of them have a timeout, builds are reproducible and idempotent (./mvnw, npm ci, pinned versions, clean workspaces), parameters have safe default values, secrets are never interpolated and never reach the log, stashes are minimal, stage names are stable and the Jenkinsfile is short because it relies on tecnoshop-lib, now at v1.1.0 with smokeSpringBoot. You know what you risk with durabilityHint('PERFORMANCE_OPTIMIZED') and why an input must not block an executor, and you have put it all into practice by reviewing the shipments-api Jenkinsfile and with a checklist you can apply to any pipeline. orders-api finishes the module as a parallel, parameterized, traceable Multibranch Pipeline backed by a versioned library; but all its builds, and those of catalog-web, still run on the controller's built-in node, the practice we have flagged as temporary more often than any other. In module 5 you will take on Laura's role as Jenkins administrator and start by solving that in Managing Jenkins Nodes and Agents, where you will connect linux-agent-01 and stop building on the controller.

© Copyright 2026. All rights reserved