At the end of the previous lesson, TecnoShop had two multibranch jobs, orders-api and catalog-web, and an uncomfortable feeling: their Jenkinsfiles repeat patterns (options, cleanup, the way tools are invoked, generating the build information), and the next service to come along will copy them yet again. Whenever Laura wants to change something shared, such as the format of build-info.txt, she will have to edit it in every repository. Jenkins Shared Libraries solve this problem: a Git repository with Groovy code that pipelines load and use as if it were Jenkins' own steps. In this lesson you will create TecnoShop's library, tecnoshop-lib, with custom steps (mavenTecnoShop and infoBuild), a utility class, a template resource and a complete pipeline template; you will configure it in Jenkins, version it with semantic tags, understand its trust model and test it with JenkinsPipelineUnit.

The Problem: Duplicated Code Across Pipelines

Fragment orders-api catalog-web Future services
Standard options (timestamps, timeout, retention) Yes Yes Yes
Invoking the build tool with standard arguments ./mvnw $MAVEN_ARGS ... in 4 places — Every Java service
Generating build-info.txt A 15-line script block Needs it and does not have it All of them
cleanWs() in cleanup Yes Yes Yes

The cost of duplication is not writing more: it is maintaining it. If build-info.txt has to include a new field tomorrow, Laura would have to open a PR in every repository, and some would be left out of date. With a shared library, the change is made once, versioned, and each team decides when to adopt it.

Structure of a Shared Library

A Shared Library is a Git repository with a fixed directory structure:

jenkins-shared-lib/
├── vars/
│   ├── mavenTecnoShop.groovy          global step: mavenTecnoShop
│   ├── mavenTecnoShop.txt             its help text
│   ├── infoBuild.groovy               global step: infoBuild
│   ├── infoBuild.txt
│   └── pipelineJavaTecnoShop.groovy   complete pipeline template
├── src/
│   └── com/tecnoshop/ci/
│       └── Version.groovy             Groovy class (package com.tecnoshop.ci)
├── resources/
│   └── com/tecnoshop/ci/
│       └── build-info.txt             text template
├── test/
│   └── groovy/                        unit tests
├── build.gradle                       for running the tests
└── README.md
Directory What it contains How it is used from the pipeline
vars/ .groovy files that define global steps: vars/infoBuild.groovy becomes the infoBuild step Directly: infoBuild application: 'x', ...
src/ Regular Groovy classes, organized in packages as in Java import com.tecnoshop.ci.Version
resources/ Files that are not code (templates, scripts, JSON) With the libraryResource step

Naming rules in vars/: the file name is the step name, in camelCase, without hyphens, and it must not clash with an existing step (a vars/sh.groovy would replace Jenkins' sh, with disastrous results).

Creating the jenkins-shared-lib Repository

  1. On GitHub, create the private repository <your-username>/jenkins-shared-lib (at TecnoShop, tecnoshop/jenkins-shared-lib), with a main branch.
  2. Extend the jenkins-tecnoshop token from 04-04: under Repository access, add jenkins-shared-lib. The permissions do not change (read-only).
  3. In the repository's Settings → Branches, protect main by requiring a pull request with a review. You will soon see why this is so important for a library.

Custom Steps in vars/: mavenTecnoShop

vars/mavenTecnoShop.groovy:

/**
 * Runs the project's Maven Wrapper with TecnoShop's standard arguments.
 *
 *   mavenTecnoShop 'clean compile'
 *   mavenTecnoShop goals: 'dependency:tree -DoutputFile=dependencies.txt', label: 'Dependency tree'
 */
def call(String goals) {
    call(goals: goals)
}

def call(Map config) {
    if (!config.goals) {
        error 'mavenTecnoShop: the "goals" parameter is missing'
    }
    String mavenArgs = env.MAVEN_ARGS ?: '-B -ntp'
    String stepLabel = config.label ?: "Maven: ${config.goals}"
    sh(script: "./mvnw ${mavenArgs} ${config.goals}", label: stepLabel)
}
  • A file in vars/ defines one or more call methods. When the pipeline writes mavenTecnoShop ..., Jenkins invokes call with the arguments.
  • There are two versions of call: one takes a string (mavenTecnoShop 'clean compile') and the other a map of named parameters (mavenTecnoShop goals: '...', label: '...'). The first delegates to the second to avoid duplicating logic.
  • Inside a library step you can use all pipeline steps (sh, error, echo...) and the env, params and currentBuild objects.
  • env.MAVEN_ARGS ?: '-B -ntp': the ?: (Elvis) operator uses MAVEN_ARGS if the Jenkinsfile defines it and, if not, the standard value. That way the step works in any project.
  • Here we do interpolate with Groovy in sh: the goals are written by the author of the Jenkinsfile (just as if they wrote them in the sh step itself); they are neither external data nor secrets. If a step ever received external data, it should pass it as environment variables, as you saw in 04-03.
  • label: each invocation appears with a readable name in the step views.

Resources and Classes: infoBuild, libraryResource and Version

The Version Class in src/

src/com/tecnoshop/ci/Version.groovy:

package com.tecnoshop.ci

class Version implements Serializable {

    private static final long serialVersionUID = 1L

    static boolean isSnapshot(String version) {
        return version != null && version.endsWith('-SNAPSHOT')
    }

    static String withoutSnapshot(String version) {
        return version?.replace('-SNAPSHOT', '')
    }

    static String imageTag(String version, String buildNumber) {
        if (!version?.trim()) {
            throw new IllegalArgumentException('The version cannot be empty')
        }
        return "${version.trim()}-${buildNumber}".toString()
    }
}
  • package com.tecnoshop.ci: must match the file's path under src/.
  • implements Serializable: pipelines save their state to disk to survive restarts (you saw this with CPS in 03-02); objects kept between steps must be serializable. Even though this class only has static methods, it is a healthy habit.
  • Static, pure methods: they take data and return data, without using pipeline steps. This is the ideal kind of code for src/, because it is easy to test. (If a class needed to run steps, it would receive the pipeline context in its constructor and call script.sh(...); it is a more advanced pattern that TecnoShop does not need.)
  • ?.: safe navigation; if version is null, it returns null instead of failing.

The Template in resources/

resources/com/tecnoshop/ci/build-info.txt:

application=@APPLICATION@
version=@VERSION@
snapshot=@SNAPSHOT@
branch=@BRANCH@
commit=@COMMIT@
build=@BUILD@
job=@JOB@
image=@IMAGE@
date=@DATE@
url=@URL@

The @...@ markers will be replaced with the real values. Separating the format from the code lets you change the file without touching any Groovy.

The infoBuild Step

vars/infoBuild.groovy:

import com.tecnoshop.ci.Version

/**
 * Generates build-info.txt from the library template and updates the build description.
 *
 *   infoBuild application: 'orders-api', version: env.APP_VERSION, image: "${env.IMAGE}:${env.IMAGE_TAG}"
 */
def call(Map config = [:]) {
    if (!config.application || !config.version) {
        error 'infoBuild: the "application" and "version" parameters are required'
    }
    String file = config.file ?: 'build-info.txt'
    String branch = env.BRANCH_NAME ?: 'unknown'
    String date = sh(script: 'date -u +%Y-%m-%dT%H:%M:%SZ', returnStdout: true, label: 'Build date').trim()

    String content = libraryResource('com/tecnoshop/ci/build-info.txt')
        .replace('@APPLICATION@', config.application)
        .replace('@VERSION@', config.version)
        .replace('@SNAPSHOT@', Version.isSnapshot(config.version) ? 'true' : 'false')
        .replace('@BRANCH@', branch)
        .replace('@COMMIT@', env.GIT_COMMIT ?: 'unknown')
        .replace('@BUILD@', env.BUILD_NUMBER)
        .replace('@JOB@', env.JOB_NAME)
        .replace('@IMAGE@', config.image ? config.image.toString() : 'no image')
        .replace('@DATE@', date)
        .replace('@URL@', env.BUILD_URL ?: '')

    writeFile file: file, text: content
    currentBuild.description = "${config.application} ${config.version} (${branch})"
    echo "infoBuild: generated ${file} for ${config.application} ${config.version}"
    return content
}
  • import com.tecnoshop.ci.Version: steps in vars/ can use the classes in src/ of the same library.
  • libraryResource('com/tecnoshop/ci/build-info.txt'): returns the contents of the file in resources/ as a string. It is the way to bring library files into the pipeline; if you needed the file on disk (for example, a script), you would write it with writeFile.
  • Chained .replace(...) calls: they replace each marker. Since they do not use regular expressions, there are no special characters to worry about.
  • env.BRANCH_NAME ?: 'unknown': the step also works in jobs that are not multibranch.
  • currentBuild.description: the step also updates the build description, so the Jenkinsfile will no longer need a script block for that.
  • return content: anyone who needs the generated text can use it.

Documenting the Steps: .txt Files

A vars/<step>.txt file documents the step. Jenkins shows it under Pipeline Syntax → Global Variables Reference in the jobs that load the library. It supports simple HTML.

vars/infoBuild.txt:

<p><b>infoBuild</b>: generates <code>build-info.txt</code> with the build's traceability data
(application, version, branch, commit, build, image, date and URL) and updates the build description.</p>
<p>Parameters: <code>application</code> (required), <code>version</code> (required),
<code>image</code> (optional), <code>file</code> (optional, defaults to <code>build-info.txt</code>).</p>
<p>Example: <code>infoBuild application: 'orders-api', version: env.APP_VERSION</code></p>

Also create vars/mavenTecnoShop.txt along the same lines. Commit and push everything to main, and create the first version:

git tag -a v1.0.0 -m "Initial version: mavenTecnoShop, infoBuild and Version"
git push origin v1.0.0

Configuring the Library in Jenkins

Manage Jenkins → System, Global Trusted Pipeline Libraries section (called Global Pipeline Libraries in earlier versions) → Add:

Field Value Explanation
Name tecnoshop-lib The name the Jenkinsfiles will load it by
Default version main The version used if the Jenkinsfile does not specify one
Load implicitly Unchecked See below
Allow default version to be overridden Checked Lets you request @v1.0.0 or another version
Include @Library changes in job recent changes Checked The library's commits appear in the Changes of the builds that use it
Cache fetched versions on controller for quick retrieval Unchecked (for now) Avoids downloading the library in every build; useful with many pipelines and pinned versions
Retrieval method Modern SCM Downloads the requested version from the repository
Source Code Management GitHub, github-tecnoshop credential, URL https://github.com/<your-username>/jenkins-shared-lib Same as in the multibranch job

When you type the Default version, Jenkins validates it and shows a message such as Currently maps to revision: 3f9a1c2.... Save.

Why not check Load implicitly? With that option, the library is loaded into every pipeline in the installation without the Jenkinsfile saying so. It seems convenient, but:

  • The dependency is invisible: someone reading the Jenkinsfile does not know where infoBuild comes from.
  • The default version (main) is always loaded: a change in the library affects every build instantly, without anyone having asked for it.
  • It is downloaded in every build, even those that do not use it.

TecnoShop prefers each Jenkinsfile to declare explicitly which library and which version it uses.

Loading the Library: @Library and library

@Library('tecnoshop-lib') _
  • An annotation at the start of the Jenkinsfile: it loads the library with the default version (main) before the pipeline is compiled, so its steps and classes are available throughout the file.
  • The _ is not a mistake: a Groovy annotation needs "something" to apply to, and _ is an empty element by convention. If you import a class, the annotation applies to the import and the _ is unnecessary:
@Library('[email protected]') import com.tecnoshop.ci.Version

Versions and variants:

Syntax Effect
@Library('tecnoshop-lib') _ Default version (main)
@Library('[email protected]') _ The v1.0.0 tag (requires Allow default version to be overridden)
@Library('tecnoshop-lib@feature/new-step') _ A branch: useful for testing library changes
@Library(['[email protected]', 'other-lib']) _ Several libraries

The library step loads a library during execution, rather than before:

  • Useful when the version is decided at run time (for example, from a parameter). The steps in vars/ become available from that moment on; the classes in src/ cannot be imported with import and are accessed through the value the step returns, which is awkward.
  • It also lets you load a library that is not configured in Jenkins, by specifying its repository:
library identifier: 'tecnoshop-lib@main', retriever: modernSCM([
    $class: 'GitSCMSource',
    remote: 'https://github.com/<your-username>/jenkins-shared-lib.git',
    credentialsId: 'github-tecnoshop'
])

A library loaded this way runs untrusted (in the sandbox), as you will see later on. At TecnoShop, @Library with a pinned version is always used.

Using the Library in orders-api and catalog-web

In orders-api three things change:

  1. The first line of the Jenkinsfile: @Library('[email protected]') _.
  2. The sh './mvnw $MAVEN_ARGS ...' calls become mavenTecnoShop '...'.
  3. The script block in Package (date, description and build-info.txt) shrinks to a single line:
                infoBuild application: 'orders-api', version: env.APP_VERSION, image: "${env.IMAGE}:${env.IMAGE_TAG}"

In catalog-web, the Build stage gains a build-info.txt it did not have before:

@Library('[email protected]') _

pipeline {
    // ... same as in 04-02 up to the Build stage ...
        stage('Build') {
            agent any
            tools {
                nodejs 'node-22'
            }
            steps {
                sh 'npm ci'
                sh 'npm run build'
                script {
                    def version = sh(script: 'node -p "require(\'./package.json\').version"',
                                     returnStdout: true, label: 'Read the version from package.json').trim()
                    infoBuild application: 'catalog-web', version: version
                }
                archiveArtifacts artifacts: 'dist/**,build-info.txt', fingerprint: true
            }
            post {
                cleanup {
                    cleanWs()
                }
            }
        }
    // ...
}
  • node -p "require('./package.json').version": -p evaluates a JavaScript expression and prints the result; here, the version from package.json. The inner single quotes are escaped (\') because the Groovy string uses single quotes.
  • The same infoBuild step generates the same format in both projects: Marta can read any TecnoShop build-info.txt without having to ask.

Make these changes on a branch in each repository and open them as PRs: the multibranch job will build the PRs with the library before they are merged. At the start of the console you will see:

Loading library [email protected]
Attempting to resolve v1.0.0 from remote references...
...

Complete Pipeline Templates: pipelineJavaTecnoShop

Besides individual steps, a library can contain an entire declarative pipeline inside a step. That way, a service's Jenkinsfile can shrink to two lines. vars/pipelineJavaTecnoShop.groovy:

/**
 * Standard pipeline for simple TecnoShop Java/Maven services.
 *
 *   @Library('[email protected]') _
 *   pipelineJavaTecnoShop(application: 'inventory-api')
 */
def call(Map config = [:]) {
    if (!config.application) {
        error 'pipelineJavaTecnoShop: the "application" parameter is missing'
    }
    String application = config.application

    pipeline {
        agent any

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

        environment {
            MAVEN_ARGS = '-B -ntp'
        }

        stages {
            stage('Build') {
                steps {
                    mavenTecnoShop 'clean compile'
                }
            }
            stage('Tests') {
                steps {
                    mavenTecnoShop 'test'
                }
            }
            stage('Package') {
                steps {
                    mavenTecnoShop '-DskipTests package'
                    script {
                        String version = sh(script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
                                            returnStdout: true, label: 'Read the version from the pom').trim()
                        infoBuild application: application, version: version
                    }
                    archiveArtifacts artifacts: 'target/*.jar,build-info.txt', fingerprint: true
                }
            }
        }

        post {
            cleanup {
                cleanWs()
            }
        }
    }
}
  • pipeline { ... } inside call: Jenkins lets you define the complete declarative pipeline in a library step. There can only be one per build.
  • A new service's Jenkinsfile would be:
@Library('[email protected]') _
pipelineJavaTecnoShop(application: 'inventory-api')
  • The map parameters (config) allow some customization, but each new option adds complexity to the template.

Individual Steps vs. Templates: TecnoShop's Decision

Individual steps (mavenTecnoShop, infoBuild) Complete template (pipelineJavaTecnoShop)
Jenkinsfile size Medium: the structure stays in the repository Minimal: two lines
Readability for the team High: stages, conditions and order are visible Low: you have to go to the library to find out what it does
Flexibility Total: each project assembles its own stages Limited to the anticipated parameters
Standardization Partial Maximum: every service is the same
Risk of a library change Affects one specific step Affects every service's entire pipeline
Trend over time Stable The template accumulates an if (config.x) for every special case

TecnoShop's decision: individual steps for orders-api and catalog-web, whose pipelines have needs of their own (smoke stage, Node matrix, deployment). The pipelineJavaTecnoShop template remains an option for simple new Java services, which will use it as long as their needs fit; when they stop fitting, they will move to their own Jenkinsfile with individual steps, rather than filling the template with special cases.

Trusted and Untrusted Libraries

Libraries configured in Manage Jenkins → System are trusted: their code runs outside the sandbox, with full access to Jenkins, just as if an administrator had written it. That is why, in a global library, a step can do things that a Jenkinsfile could not do without approving signatures (as you saw in 03-06).

Global library (trusted) Folder library / library with a repository (untrusted)
Where it is configured Manage Jenkins → System Configure on a folder or multibranch job, Pipeline Libraries section; or with library identifier:
Sandbox No Yes, like a Jenkinsfile
Who should be able to modify it Only the platform team, with review The team that owns the folder

The consequence is serious: anyone who can modify tecnoshop-lib effectively has administrator permissions on Jenkins. And since Allow default version to be overridden is checked, a Jenkinsfile can request any branch or tag of the library repository: if someone could push a branch to jenkins-shared-lib without review, they could run their code with full trust by requesting @Library('tecnoshop-lib@their-branch'). That is why Laura:

  • Restricts write access to the jenkins-shared-lib repository to the platform team, with main protected and review required (done when it was created).
  • Protects the v* tags so that nobody can move them.
  • Keeps privileged logic to a minimum: the fact that a library can bypass the sandbox does not mean it should.

Jenkins' full permission model is configured in Configuring Security.

Versioning and Releasing New Versions

TecnoShop versions the library with semantic tags vMAJOR.MINOR.PATCH:

Change Example New version
Compatible fix infoBuild failed without GIT_COMMIT v1.0.1
New compatible feature A new step, or a new optional parameter v1.1.0
Breaking change A required parameter is renamed or the build-info.txt format changes v2.0.0

The workflow for releasing a version without breaking anyone:

flowchart LR
    A["Library branch<br/>feature/new-step"] --> B["PR in jenkins-shared-lib<br/>(tests + review)"]
    A -.->|"@Library('tecnoshop-lib@feature/new-step')"| C["Test PR in orders-api<br/>multibranch build"]
    B --> D["Merge to main"]
    D --> E["git tag v1.1.0"]
    E --> F["PR in each consumer:<br/>@v1.0.0 → @v1.1.0"]
  1. The change is developed on a library branch and tested with its unit tests.
  2. Before merging, it is tested in a real consumer: a PR in orders-api that uses @Library('tecnoshop-lib@feature/new-step') _. The multibranch job builds it without affecting main. That PR is not merged.
  3. It is merged into the library's main and the v1.1.0 tag is created.
  4. Each project updates its @Library in a PR of its own, when it suits it. Projects still on v1.0.0 notice nothing.

For breaking changes (v2.0.0), Laura notifies the teams and keeps maintaining v1.x with fixes for a while. Some organizations also keep a v1 branch that moves forward with each compatible version, so that consumers get fixes without editing the Jenkinsfile; it is a trade-off between convenience and control. TecnoShop prefers pinned versions: every version change goes through a PR and a build.

Unit Testing with JenkinsPipelineUnit

A library is code that every pipeline depends on: it deserves tests. JenkinsPipelineUnit is a framework that runs library steps (and Jenkinsfiles) outside Jenkins, mocking pipeline steps (sh, echo, error...) and recording every call so you can check it.

build.gradle

plugins {
    id 'groovy'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.codehaus.groovy:groovy:3.0.22'
    testImplementation 'com.lesfurets:jenkins-pipeline-unit:1.23'
    testImplementation platform('org.junit:junit-bom:5.10.2')
    testImplementation 'org.junit.jupiter:junit-jupiter'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

sourceSets {
    main {
        groovy {
            srcDirs = ['src']
        }
    }
    test {
        groovy {
            srcDirs = ['test/groovy']
        }
    }
}

test {
    useJUnitPlatform()
}
  • id 'groovy': compiles Groovy code with Gradle.
  • srcDirs = ['src']: the library classes (Version) are in src/, not in Gradle's default path. The steps in vars/ are not compiled: JenkinsPipelineUnit loads them as scripts during the tests.
  • jenkins-pipeline-unit: the framework. The versions shown are a guide: check Maven Central for the latest com.lesfurets:jenkins-pipeline-unit and use the Groovy version compatible with it.

Testing a Class from src/

test/groovy/com/tecnoshop/ci/VersionTest.groovy:

package com.tecnoshop.ci

import org.junit.jupiter.api.Test

import static org.junit.jupiter.api.Assertions.*

class VersionTest {

    @Test
    void detectsSnapshotVersions() {
        assertTrue(Version.isSnapshot('1.0.0-SNAPSHOT'))
        assertFalse(Version.isSnapshot('1.0.0'))
        assertFalse(Version.isSnapshot(null))
    }

    @Test
    void buildsTheImageTag() {
        assertEquals('1.0.0-SNAPSHOT-42', Version.imageTag('1.0.0-SNAPSHOT', '42'))
    }

    @Test
    void rejectsEmptyVersion() {
        assertThrows(IllegalArgumentException) { Version.imageTag(' ', '42') }
    }
}

A regular JUnit 5 test: Version does not depend on Jenkins.

Testing a Step from vars/

test/groovy/MavenTecnoShopTest.groovy:

import com.lesfurets.jenkins.unit.BasePipelineTest
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test

import static org.junit.jupiter.api.Assertions.*

class MavenTecnoShopTest extends BasePipelineTest {

    @Override
    @BeforeEach
    void setUp() throws Exception {
        super.setUp()
        binding.setVariable('env', [MAVEN_ARGS: '-B -ntp'])
    }

    @Test
    void runsTheWrapperWithTheStandardArguments() {
        def step = loadScript('vars/mavenTecnoShop.groovy')

        step.call('clean compile')

        def shCalls = helper.callStack.findAll { it.methodName == 'sh' }
        assertEquals(1, shCalls.size())
        assertTrue(callArgsToString(shCalls[0]).contains('./mvnw -B -ntp clean compile'))
    }

    @Test
    void failsWhenGoalsAreMissing() {
        def step = loadScript('vars/mavenTecnoShop.groovy')

        assertThrows(Exception) { step.call([:]) }
    }
}
  • extends BasePipelineTest: JenkinsPipelineUnit's base class. Its setUp() registers mocked versions of the most common steps; that is why we call it with super.setUp().
  • binding.setVariable('env', [...]): mocks the env object with the values we want for the test.
  • loadScript('vars/mavenTecnoShop.groovy'): loads the step the way Jenkins would.
  • helper.callStack: the list of every step call that has been made. We filter the sh calls and check that there was exactly one, with the expected command (callArgsToString turns its arguments into text).
  • failsWhenGoalsAreMissing: the mocked error throws an exception, just as it stops the build in Jenkins.

Run the tests with Gradle installed (gradle test) or with a container, without installing anything:

docker run --rm -v "$PWD":/home/gradle/lib -w /home/gradle/lib gradle:8-jdk21 gradle test

The natural next step is for the jenkins-shared-lib repository itself to have a Jenkinsfile that runs these tests on every PR, with its own multibranch job. You will do that in exercise 3.

The Updated Jenkinsfile

@Library('[email protected]') _

pipeline {
    agent any

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

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

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

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

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

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

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

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

Changes compared with 04-05:

  • First line: @Library('[email protected]') _.
  • Every Maven invocation uses mavenTecnoShop.
  • Package no longer has a script block: infoBuild generates build-info.txt (now also with the snapshot= line) and updates the description.

Common Mistakes and Tips

  • No such DSL method 'infoBuild': the Jenkinsfile has no @Library, the library name does not match the configured one, or the file in vars/ has a different name.
  • ERROR: Could not resolve v1.0.0 (or similar) when loading the library: the tag does not exist in the repository, it has not been pushed (git push origin v1.0.0) or the token has no access to jenkins-shared-lib.
  • Version v1.0.0 to use for library tecnoshop-lib is not permitted (or a similar message): Allow default version to be overridden is not checked.
  • Forgetting the _ after @Library(...): a Jenkinsfile compilation error.
  • Step names with hyphens (info-build.groovy): they are not valid Groovy identifiers. Use camelCase.
  • Non-serializable src/ classes stored in pipeline variables: NotSerializableException, as you saw in 03-02.
  • Enabling Load implicitly "for convenience": invisible dependencies and changes that reach every pipeline without warning.
  • Using @Library('tecnoshop-lib') _ without a version in stable projects: any commit to the library's main changes their build immediately.
  • Giving anyone write access to the library: it is equivalent to giving them administrator access to Jenkins.
  • Tip: keep steps small, with a clear responsibility, documented in their .txt and covered by tests. A library nobody understands is worse than the duplication it was meant to avoid.

Exercises

Exercise 1. Add an optional extra parameter (a map) to infoBuild whose entries are appended to the end of build-info.txt as key=value lines. For example, infoBuild application: 'catalog-web', version: version, extra: [node: 'node-22']. What version number should the library get after this change? Write out the complete workflow for releasing it.

Exercise 2. A colleague proposes this implementation of a vars/announceBranch.groovy step. Find the problems and fix them:

def call() {
    sh "echo Building branch ${env.BRANCH_NAME} of PR ${env.CHANGE_TITLE}"
    def f = new File("${env.WORKSPACE}/branch.txt")
    f.text = env.BRANCH_NAME
}

Exercise 3. Create a Jenkinsfile for the jenkins-shared-lib repository itself that runs the unit tests with Gradle on every branch and PR, and create the jenkins-shared-lib multibranch job to build it. Hint: the built-in node does not have Gradle; add the Gradle Wrapper to the repository (gradle wrapper, which generates gradlew and gradle/wrapper/), just as orders-api uses the Maven Wrapper.

Solutions

Solution 1. At the end of call, before writeFile:

    if (config.extra) {
        config.extra.each { key, value ->
            content += "${key}=${value}\n"
        }
    }

For this, content must be declared with def or String without final, as it already is. It is a new compatible feature (the parameter is optional and anyone who does not use it gets the same file), so it corresponds to v1.1.0. Workflow: a feature/infobuild-extra branch in jenkins-shared-lib → a new unit test that checks that writeFile receives the extra lines → a test PR in catalog-web with @Library('tecnoshop-lib@feature/infobuild-extra') _ → review and merge in the library → git tag -a v1.1.0 -m "infoBuild: extra parameter" and git push origin v1.1.0 → a PR in catalog-web switching to @v1.1.0 and using extra. orders-api stays on v1.0.0 until it decides to upgrade.

Solution 2. Problems: (1) command injection: BRANCH_NAME and, above all, CHANGE_TITLE are external data interpolated with Groovy into an sh step; moreover, since this is a trusted library, the mistake is even more serious. (2) new File(...) runs on the controller, not on the agent: it would write to the controller's disk (or fail) instead of to the build's workspace; in a trusted library not even the sandbox stops it. (3) CHANGE_TITLE does not exist outside PRs. Fix:

def call() {
    echo "Building branch ${env.BRANCH_NAME}" + (env.CHANGE_TITLE ? " of PR ${env.CHANGE_TITLE}" : '')
    writeFile file: 'branch.txt', text: (env.BRANCH_NAME ?: 'unknown')
}

echo does not go through the shell, and writeFile writes to the agent's workspace.

Solution 3. After running gradle wrapper locally (or with the Gradle container) and pushing gradlew, gradlew.bat and gradle/wrapper/ (with git update-index --chmod=+x gradlew if you work on Windows):

pipeline {
    agent any
    options {
        timestamps()
        timeout(time: 15, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '20'))
    }
    stages {
        stage('Library tests') {
            steps {
                sh './gradlew --no-daemon test'
            }
        }
    }
    post {
        cleanup {
            cleanWs()
        }
    }
}

--no-daemon avoids leaving a Gradle process running in the background on the controller. Create the jenkins-shared-lib multibranch job with the same configuration as orders-api. From then on, no library PR should be merged without a green build. (The JUnit results will be published in Jenkins once you see the junit step in 06-03.)

Conclusion

TecnoShop now has its Shared Library, tecnoshop-lib: a repository with vars/ for global steps (mavenTecnoShop, infoBuild and the pipelineJavaTecnoShop template), src/ for classes such as com.tecnoshop.ci.Version and resources/ for files read with libraryResource, such as the build-info.txt template. You know how to configure it as a Global Trusted Pipeline Library (default version main, no implicit loading, overridable versions and the github-tecnoshop credential), load it with @Library('[email protected]') _ or with the library step, and why a trusted library requires protecting its repository as if it were Jenkins administration itself. You have chosen between individual steps and complete templates, you version with semantic tags following a workflow that breaks nobody, and you test the library with JenkinsPipelineUnit. The orders-api Jenkinsfile is now shorter and has no script blocks. With all the pieces of the module in hand, what remains is the judgment to use them well. In the last lesson of the module, Pipeline Best Practices, you will review the practices that separate a pipeline that works from a maintainable pipeline, review a problematic Jenkinsfile and finalize the one for orders-api.

© Copyright 2026. All rights reserved