Since module 1, orders-api has been built with the Maven Wrapper and catalog-web with npm, and the rule from 04-07 is clear: Jenkins orchestrates and the tool builds. But "orchestrating well" involves decisions you have not made yet: which version of the tool is used and who pins it, where the configuration that should not live in every repository comes from (Maven's settings.xml or npm's .npmrc, which in the next step will point to the company's artifact repository), what is cached on the agent and with what risks, and what the plugins that integrate Maven with Jenkins bring to the table. In this lesson you will dig into Maven, Gradle and npm inside Jenkins: you will install the Config File Provider plugin so the platform manages settings.xml and .npmrc, adapt the library's mavenTecnoShop step in a new version, evaluate the Pipeline Maven Integration plugin, build a sample Gradle service and review how other common tools are invoked, always with pinned versions so that builds are reproducible.

What Jenkins Should Provide to a Build Tool

A build tool (Maven, Gradle, npm...) knows how to compile, test and package. What it lacks to work on a shared server is context, and that is what Jenkins provides:

Need Who takes care of it at TecnoShop
The tool, in a specific version The repository wrapper (./mvnw, ./gradlew) or an installation with a stable name (node-22)
The JDK The linux-agent-01 agent image (JDK 21)
Company configuration (repositories, mirrors, credentials) Files managed by Jenkins with Config File Provider
Secrets Jenkins credentials, injected when needed
Dependency cache Directories on the agent volume, configured with node variables
Standard arguments MAVEN_ARGS and the library's mavenTecnoShop step

What Jenkins should not do is replace the tool: no looping over modules with Groovy and no copying files "by hand" with pipeline steps.

Maven: Wrapper vs. Installed Tool

There are two ways to have Maven in a Jenkins build:

(a) A tool installed by Jenkins. In Manage Jenkins → Tools → Maven installations → Add Maven, you define a named installation (for example, maven-3.9) and check Install automatically → Install from Apache with a specific version. In the pipeline you request it like this:

pipeline {
    agent { label 'linux' }
    tools {
        maven 'maven-3.9'
    }
    stages {
        stage('Build') {
            steps {
                sh 'mvn -B -ntp clean compile'
            }
        }
    }
}
  • tools { maven 'maven-3.9' }: Jenkins downloads that version to the agent the first time (into tools/, inside the node's root directory) and puts it on the build's PATH.
  • mvn: the installed Maven command, not the wrapper.

(b) Maven Wrapper, which is what orders-api has used since 01-04: the repository includes mvnw and .mvn/wrapper/maven-wrapper.properties, which says which version to download.

Aspect Jenkins tool (tools) Maven Wrapper (./mvnw)
Where the version is pinned In the Jenkins configuration In the repository, next to the code
Who changes it The administrator, for every project using that name The project team, with a PR
Same Maven locally and in CI Only if every developer installs the same version Yes, automatically
Projects with different versions One installation per version (maven-3.8, maven-3.9...) Each one has its own
Requirements on the agent None None (just the JDK)

TecnoShop uses the wrapper: the tool version is part of the code and travels with it, and Diego builds on his laptop exactly the way Jenkins does. The Maven installations section can stay empty.

The Maven Version, Pinned in the Repository

The .mvn/wrapper/maven-wrapper.properties file in orders-api looks something like this:

wrapperVersion=3.3.2
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip
  • wrapperVersion: the version of the wrapper itself.
  • distributionType=only-script: the modern wrapper does not need an auxiliary .jar in the repository; mvnw is just a script.
  • distributionUrl: the exact Maven distribution that is downloaded the first time and stored in ~/.m2/wrapper/. The versions in this example are indicative; yours will be the ones your project generated.

To upgrade Maven, the team runs this on their machine:

./mvnw wrapper:wrapper -Dmaven=3.9.11
git add .mvn/wrapper/maven-wrapper.properties mvnw mvnw.cmd
git commit -m "Upgrade Maven to 3.9.11"
  • wrapper:wrapper -Dmaven=...: regenerates the wrapper files with the requested version.
  • The change arrives through a PR and the multibranch builds it before it is merged.

You can add distributionSha256Sum=<sum> to the file so the wrapper checks the integrity of the downloaded distribution; if someone tampered with it on the way, the build would fail.

A note on MAVEN_ARGS. Since Maven 3.9, the tool itself reads the MAVEN_ARGS environment variable and prepends its contents to the command-line arguments. Because mavenTecnoShop also adds it explicitly, you will see -B -ntp repeated in the effective command line; it is harmless.

Managed Configuration with Config File Provider

Some configuration does not belong to a project, but to the company: which artifact repository Maven connects to, which credentials it publishes with, which package registry npm uses. If every repository carried its own copy, changing the server would mean touching every project, and the credentials would end up in Git.

The Config File Provider plugin (config-file-provider) lets you store configuration files in Jenkins and hand them to the build only while it needs them. Install it and add it to the plugins.txt from 05-04.

Once it is installed, Manage Jenkins → Managed files appears. With Add a new Config you choose the file type:

Type Use Provided by
Maven settings.xml User settings.xml (Maven's -s option) Config File Provider
Global Maven settings.xml Global settings.xml (the -gs option) Config File Provider
Npm config file .npmrc with registries and credentials NodeJS plugin
Custom file, Json file, Xml file... Any other file Config File Provider

Files can be defined in Managed files (for the whole installation) or in the configuration of a folder (only for the jobs it contains), just like the credentials in 04-04.

The maven-settings-tecnoshop File

Manage Jenkins → Managed files → Add a new Config → Maven settings.xml. In ID, type maven-settings-tecnoshop (if you leave it empty, Jenkins generates an unreadable UUID) and click Next.

Field Value
Name maven-settings-tecnoshop
Comment settings.xml for the TecnoShop Maven builds. The Nexus mirror is enabled in 06-05. Owner: Laura.
Replace All Checked (you will use it in 06-05 with Server Credentials)
Content The following XML
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.2.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.2.0 https://maven.apache.org/xsd/settings-1.2.0.xsd">

    <!-- Managed from Jenkins (Managed files). Do not copy it into the repositories. -->
    <interactiveMode>false</interactiveMode>

    <!--
      Mirror to the TecnoShop Nexus: it will be enabled in 06-05, once Nexus exists.
      At TecnoShop: https://nexus.tecnoshop.local/repository/maven-public/
      In the lab: http://nexus:8081/repository/maven-public/
    <mirrors>
        <mirror>
            <id>nexus-tecnoshop</id>
            <name>TecnoShop Nexus (maven-public group)</name>
            <mirrorOf>*</mirrorOf>
            <url>http://nexus:8081/repository/maven-public/</url>
        </mirror>
    </mirrors>
    -->
</settings>
  • <interactiveMode>false</interactiveMode>: Maven will never try to ask anything (in CI there is nobody to answer). It is the same as -B, but set in the configuration.
  • The <mirrors> block, commented out for now: a mirror with <mirrorOf>*</mirrorOf> makes every dependency download go through the company Nexus instead of Maven Central. You will enable it in Artifact and Image Repositories, together with the publishing credentials.

Today the file barely changes the behavior. What matters is that the plumbing is in place: when Laura changes the content, every build will receive it without touching a single repository.

configFileProvider in the Pipeline

The step that hands a managed file to the build is configFileProvider:

configFileProvider([configFile(fileId: 'maven-settings-tecnoshop', variable: 'MAVEN_SETTINGS')]) {
    sh './mvnw -s "$MAVEN_SETTINGS" -B -ntp clean compile'
}
  • configFile(fileId: 'maven-settings-tecnoshop', ...): which managed file you want.
  • variable: 'MAVEN_SETTINGS': inside the block, the MAVEN_SETTINGS environment variable contains the path of the temporary file Jenkins has written on the agent (in an auxiliary workspace directory, something like orders-api_main@tmp/config...tmp).
  • -s "$MAVEN_SETTINGS": Maven uses that settings.xml. Single quotes in Groovy and double quotes in the shell, as you learned in 04-03.
  • When the block exits, Jenkins deletes the file. If it contains credentials (it will in 06-05), they only exist on the agent's disk for as long as the block lasts.
  • The optional targetLocation parameter lets you write it to a specific path in the workspace; you do not need it.

The Snippet Generator (03-06) generates this step from configFileProvider: Provide Configuration files.

mavenTecnoShop with Settings: tecnoshop-lib v1.2.0

orders-api does not call ./mvnw directly, but through mavenTecnoShop. The natural thing is for the library step to be the one that uses the managed settings. Laura adapts it following the versioning workflow from 04-06.

vars/mavenTecnoShop.groovy on the feature/maven-settings branch of jenkins-shared-lib:

/**
 * Runs the project's Maven Wrapper with the TecnoShop standard arguments.
 *
 *   mavenTecnoShop 'clean compile'
 *   mavenTecnoShop goals: 'dependency:tree -DoutputFile=dependencies.txt', label: 'Dependency tree'
 *   mavenTecnoShop goals: 'verify', settings: 'maven-settings-tecnoshop'
 *
 * If "settings" is not given, env.MAVEN_SETTINGS_ID is used (if it exists).
 */
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}"
    String settingsId = config.settings ?: env.MAVEN_SETTINGS_ID

    if (settingsId) {
        configFileProvider([configFile(fileId: settingsId, variable: 'MAVEN_SETTINGS')]) {
            sh(script: "./mvnw -s \"\$MAVEN_SETTINGS\" ${mavenArgs} ${config.goals}", label: stepLabel)
        }
    } else {
        sh(script: "./mvnw ${mavenArgs} ${config.goals}", label: stepLabel)
    }
}

What changes compared with v1.1.0:

  • Optional settings parameter: the ID of a managed file. If it is not passed, the step looks at env.MAVEN_SETTINGS_ID, just as it already did with MAVEN_ARGS. That way a Jenkinsfile declares it once in environment and does not repeat it on every call.
  • Without settings, the behavior is identical to before. That is why it is a compatible change.
  • \"\$MAVEN_SETTINGS\": inside a double-quoted Groovy string, \$ stops Groovy from trying to interpolate MAVEN_SETTINGS (which is not a Groovy variable) and leaves $MAVEN_SETTINGS for the shell; \" produces the double quotes that protect the path.

Add a test to test/groovy/MavenTecnoShopTest.groovy:

    @Test
    void usesTheManagedSettingsWhenGiven() {
        helper.registerAllowedMethod('configFile', [Map], { map -> map })
        helper.registerAllowedMethod('configFileProvider', [List, Closure], { list, body -> body() })
        def step = loadScript('vars/mavenTecnoShop.groovy')

        step.call(goals: 'clean compile', settings: 'maven-settings-tecnoshop')

        assertTrue(helper.callStack.any { it.methodName == 'configFileProvider' })
        def shCalls = helper.callStack.findAll { it.methodName == 'sh' }
        assertTrue(callArgsToString(shCalls[0]).contains('./mvnw -s "$MAVEN_SETTINGS" -B -ntp clean compile'))
    }
  • registerAllowedMethod: JenkinsPipelineUnit does not know the Config File Provider steps, so they are mocked. configFile returns the map it receives and configFileProvider simply runs the block (body()).
  • The assertions verify that configFileProvider was used and that the command includes -s "$MAVEN_SETTINGS".

Update vars/mavenTecnoShop.txt with the new parameter, test the branch from an orders-api PR with @Library('tecnoshop-lib@feature/maven-settings') _, merge and release:

git tag -a v1.2.0 -m "mavenTecnoShop: managed settings.xml (settings parameter and MAVEN_SETTINGS_ID)"
git push origin v1.2.0

The Change in orders-api

Only two lines of the Jenkinsfile change:

@Library('[email protected]') _

pipeline {
    // ... agent, options, parameters and triggers unchanged ...

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

    // ... stages and post unchanged ...
}

In the console, each Maven step now appears wrapped by the file provider:

[Pipeline] configFileProvider
provisioning config files...
copy managed file [maven-settings-tecnoshop] to file:/home/jenkins/agent/workspace/orders-api_main@tmp/config1234567890tmp
[Pipeline] {
[Pipeline] sh (Maven: clean compile)
+ ./mvnw -s /home/jenkins/agent/workspace/orders-api_main@tmp/config1234567890tmp -B -ntp -B -ntp clean compile
...
[Pipeline] }
Deleting 1 temporary files

Reading APP_VERSION still calls ./mvnw without settings; it is a local query of pom.xml that does not need the company configuration. smokeSpringBoot does not use Maven and does not change. catalog-web does not use Maven and stays on v1.0.0.

Pipeline Maven Integration (withMaven)

The Pipeline Maven Integration plugin (pipeline-maven) offers a different approach: wrapping Maven commands in a withMaven step that prepares the environment and, when it finishes, automatically publishes whatever it finds.

withMaven(maven: 'maven-3.9', mavenSettingsConfig: 'maven-settings-tecnoshop') {
    sh 'mvn -B verify'
}
  • maven: 'maven-3.9': the Tools installation to use (recent versions also support the wrapper; check its documentation).
  • mavenSettingsConfig: the ID of a Config File Provider file.

What it brings and what it costs:

Benefits Drawbacks
Injects settings, JDK and Maven options Implicit behavior: it publishes reports and archives files without the Jenkinsfile saying so
Automatically publishes Surefire/Failsafe results, JaCoCo, generated artifacts and dependency fingerprints It can duplicate what you already do with explicit steps (junit, archiveArtifacts)
Can trigger downstream jobs when a SNAPSHOT dependency they depend on is built Needs a database (H2 in JENKINS_HOME by default; an external one is recommended for large installations)
Shows in the build which dependencies and artifacts were used Adds a "spy" to the Maven execution: a bit more time and more complexity when troubleshooting
The build in Jenkins is no longer identical to the one the developer runs on their machine

Publishers can be disabled one by one (options: [junitPublisher(disabled: true)]), or you can ask for only the explicitly enabled ones to run (publisherStrategy: 'EXPLICIT'), but then much of its appeal is lost.

TecnoShop's decision: it does not adopt it. It prefers the Jenkinsfile to state explicitly what gets published (you will see junit and recordCoverage in the next lesson) and the settings to arrive with the standard configFileProvider step through mavenTecnoShop. It is a direct application of the "visible dependencies" principle you already defended when you left Load implicitly unchecked for the library. For organizations with dozens of Maven projects chained together by SNAPSHOT dependencies, automatic downstream triggering can make up for its drawbacks.

The Dependency Cache on Agents and Its Risks

In 05-01 Laura set the node variable MAVEN_OPTS=-Dmaven.repo.local=/home/jenkins/agent/.m2/repository, so the local Maven repository lives on the linux_agent_01 volume and survives the container being recreated. That cache speeds builds up a lot (the first one downloads hundreds of files; the following ones, almost nothing), but you should know its risks:

Risk What can happen Mitigation at TecnoShop
Concurrent access Two executors write the same file at the same time and one ends up corrupt (odd checksum or zip END header not found errors) Maven 3.9 handles concurrency better; if it happens, the affected artifact is deleted from the cache
Contamination through install A build installs one of its own artifacts in the cache, and other builds later use it instead of the published one Never install in CI (04-07); publishing will come with deploy in 06-05
Poisoning from a PR A malicious PR adds an external repository and leaves a tampered version of a dependency in the shared cache, which the next main build will use A single mirror to Nexus (06-05); the Trust policy from 04-05; in the long run, ephemeral agents for PRs (module 8)
Unbounded growth The agent's disk fills up with old versions Free Disk Space monitor; periodic cleanup of the directory (Maven repopulates it)
Builds that "work by accident" A dependency that has disappeared from the remote repository is still in the cache and the build passes; on a clean agent it would fail A periodic build on a clean agent (with ephemeral agents, every build is one)

The simplest cleanup, during a window with no builds:

docker compose exec linux-agent-01 rm -rf /home/jenkins/agent/.m2/repository

The next build of each project will take longer, because it will download everything again. That is the price of a known state.

Gradle in Jenkins: The recommendations-api Service

TecnoShop's marketing team is preparing a new service, recommendations-api (fictitious), with Gradle. The ideas are the same as with Maven: a versioned wrapper, standard arguments and a cache on the agent volume.

The Gradle Wrapper

gradle/wrapper/gradle-wrapper.properties:

distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
distributionSha256Sum=<sha256-sum-published-by-gradle>
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
  • distributionUrl: the exact Gradle version (indicative in the example). The backslash in https\: is how you escape : in a .properties file.
  • distributionSha256Sum: Gradle publishes the checksum of each distribution; with it, the wrapper rejects a tampered download.
  • zipStoreBase=GRADLE_USER_HOME: distributions are stored in the user's Gradle directory.

The Gradle Cache on the Agent

Just as with MAVEN_OPTS, Laura adds the variable GRADLE_USER_HOME=/home/jenkins/agent/.gradle in the Node Properties of linux-agent-01, so that distributions, dependencies and the build cache live on the volume.

The Jenkinsfile

pipeline {
    agent {
        label 'linux'
    }

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

    environment {
        GRADLE_ARGS = '--no-daemon --console=plain --build-cache'
    }

    stages {
        stage('Build') {
            steps {
                sh './gradlew $GRADLE_ARGS clean assemble'
            }
        }
        stage('Tests') {
            steps {
                sh './gradlew $GRADLE_ARGS test'
            }
        }
    }

    post {
        cleanup {
            cleanWs()
        }
    }
}
  • ./gradlew: the wrapper, never an installed gradle.
  • --no-daemon: does not leave a Gradle process running at the end. The daemon speeds up successive builds on a developer's machine, but on an agent shared by several projects it uses memory between builds, can carry state over and, on ephemeral agents, adds nothing. TecnoShop disables it; with permanent agents heavily loaded with builds of the same project, the opposite might be worth considering, with measurements.
  • --console=plain: output without animated progress bars, readable in the Jenkins console.
  • --build-cache: enables the build cache, which reuses the results of tasks whose inputs have not changed (for example, it does not recompile an identical module).
  • './gradlew $GRADLE_ARGS ...' with single quotes: the shell expands the variable, as with MAVEN_ARGS.
  • clean assemble and then test: compile and package first and test afterward, to fail fast, just as in orders-api.

Local Cache and Remote Cache

The local build cache lives in GRADLE_USER_HOME. Gradle also supports a shared remote cache (for example, an HTTP cache node), configured in settings.gradle:

buildCache {
    remote(HttpBuildCache) {
        url = 'https://gradle-cache.tecnoshop.local/cache/'
        push = System.getenv('BRANCH_NAME') == 'main'
    }
}
  • push = ... == 'main': only main builds write to the remote cache; PRs and developers only read. It is the same concern as poisoning the Maven cache: a PR must not be able to leave results that others reuse.

Gradle's test reports (build/test-results/test/*.xml) will be published with the junit step in 06-03.

npm in Depth in catalog-web

npm ci vs. npm install

catalog-web has used npm ci since 04-02. The difference is essential in CI:

Aspect npm install npm ci
Source of the versions package.json (ranges such as ^29.7.0) and, if it exists, the lockfile Only package-lock.json
If package.json and the lockfile do not match Updates the lockfile Fails with an error
Writes to package-lock.json Yes, it may modify it Never
Existing node_modules Reuses and modifies it Deletes it and installs from scratch
Result May vary between two runs Always identical for the same lockfile
Use Development: adding or updating dependencies CI and any reproducible build

If npm ci fails with a message such as npm ci can only install packages when your package.json and package-lock.json are in sync, the fix is not to switch to npm install in the Jenkinsfile: it is for the developer to run npm install on their machine and push the updated lockfile.

The npm Cache on the Agent

npm keeps downloaded packages in its cache, by default in ~/.npm (/home/jenkins/.npm), outside the agent volume. Laura adds the variable npm_config_cache=/home/jenkins/agent/.npm in the Node Properties of linux-agent-01.

  • npm treats any npm_config_<option> environment variable as a configuration option; this one changes the cache location.
  • The npm cache is designed for concurrent access and verifies the integrity of every package, so the three matrix cells can share it.
  • npm ci --prefer-offline uses the cache without asking the registry if the package is already there, which speeds up the matrix cells.

A Managed .npmrc: npmrc-tecnoshop

npm reads its configuration from .npmrc files: the project one (in the repository), the user one and the global one. For the company registry and its credentials, TecnoShop uses an .npmrc managed by Jenkins. The NodeJS plugin (which you installed in 04-02) adds the Npm config file type to Config File Provider.

Manage Jenkins → Managed files → Add a new Config → Npm config file, ID npmrc-tecnoshop:

# .npmrc for the TecnoShop builds (managed from Jenkins)
registry=https://registry.npmjs.org/
# In 06-05: registry=http://nexus:8081/repository/npm-public/
fund=false
update-notifier=false
  • registry: the public registry, for now. In 06-05 it will point to the Nexus npm-public group.
  • fund=false and update-notifier=false: remove package funding messages and new npm version notices that only clutter the log.
  • The Npm config file form also has an NPM Registry section where you can associate a registry with a Jenkins credential; the plugin adds the authentication to the file when it hands it over. You will use it if the private registry requires credentials.
  • Dependency vulnerability scanning (npm audit) is part of supply chain security and is covered in DevSecOps: Security in the Pipeline.

Remember npm's precedence: a project .npmrc takes precedence over the user one. catalog-web does not have one; if it did, its values would win over the platform's.

The Changes in the catalog-web Jenkinsfile

The nodejs step accepts the configId parameter, which hands over the managed file as npm's user configuration for the duration of the block:

        stage('Tests per Node version') {
            matrix {
                axes {
                    axis {
                        name 'NODE_VERSION'
                        values 'node-18', 'node-20', 'node-22'
                    }
                }
                agent {
                    label 'linux'
                }
                stages {
                    stage('Test') {
                        steps {
                            nodejs(nodeJSInstallationName: env.NODE_VERSION, configId: 'npmrc-tecnoshop') {
                                sh 'node --version && npm --version'
                                sh 'npm ci --prefer-offline'
                                sh 'npm test'
                            }
                        }
                        post {
                            cleanup {
                                cleanWs()
                            }
                        }
                    }
                }
            }
        }

        stage('Build') {
            agent {
                label 'linux'
            }
            steps {
                nodejs(nodeJSInstallationName: 'node-22', configId: 'npmrc-tecnoshop') {
                    sh 'npm ci --prefer-offline'
                    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()
                }
            }
        }
  • configId: 'npmrc-tecnoshop': the managed .npmrc applies to every npm command in the block.
  • In Build, the tools { nodejs 'node-22' } directive is replaced with the nodejs(...) step, because tools does not support configId. The effect on the PATH is the same.
  • --prefer-offline: takes advantage of the agent's cache.

Maven, Gradle and npm in CI: A Comparison

Aspect Maven Gradle npm
Tool version Maven Wrapper (./mvnw) Gradle Wrapper (./gradlew) Jenkins installation (node-22) + engines in package.json
Dependency versions Exact in pom.xml (except ranges, which are discouraged) In build.gradle; optional lockfiles package-lock.json + npm ci
Non-interactive mode -B --console=plain --ci in Jest; npm does not prompt in ci
Company configuration Managed settings.xml (-s) init.gradle or gradle.properties in GRADLE_USER_HOME Managed .npmrc (configId)
Dependency cache maven.repo.local on the volume GRADLE_USER_HOME on the volume npm_config_cache on the volume
Task result cache No (beyond incremental compilation) Yes: local and remote build cache No
Resident process No Daemon (disabled at TecnoShop) No
Typical CI command ./mvnw -B -ntp verify ./gradlew --no-daemon build npm ci && npm test && npm run build
Test reports (06-03) target/surefire-reports/*.xml build/test-results/test/*.xml With a JUnit reporter (jest-junit)

Other Build Tools

Jenkins does not need a plugin for every tool: all it takes is for the tool to be on the agent (or provided by a wrapper or a Tools installation) and to call it with sh.

Ecosystem Tool Typical CI command How to pin the version
C/C++ and generic make make -j"$(nproc)" all test Agent image or container
.NET dotnet dotnet restore --locked-mode && dotnet build -c Release --no-restore && dotnet test --no-build global.json with the SDK version
Go go go build ./... && go test ./... go / toolchain directive in go.mod
Python with pip pip python -m venv .venv && .venv/bin/pip install -r requirements.txt && .venv/bin/pytest requirements.txt with exact versions (==) or with hashes
Python with Poetry poetry poetry install --no-interaction && poetry run pytest poetry.lock

Two patterns repeat across all of them: an isolated environment per build (Python's venv, the node_modules from npm ci) and a version lock file in the repository. When a tool is not on the agent, the long-term answer is not to install it by hand on linux-agent-01, but to run the build in a container that has the tool, as you will see in Jenkins with Docker.

Reproducibility: Pin the Versions of Everything

A build is reproducible if the same commit produces the same result at any time and on any agent. Review what is pinned at TecnoShop and where:

Piece Where it is pinned Status
Maven .mvn/wrapper/maven-wrapper.properties Pinned
Java dependencies pom.xml with exact versions (and the Spring Boot parent) Pinned
JDK Agent image Partial: jenkins/inbound-agent:latest-jdk21 pins the major version, not the exact one. Laura will pin it when she builds custom images in 08-01
Node node-18, node-20, node-22 installations in Tools Pinned by name; each installation points to a specific version that Laura changes deliberately
npm dependencies package-lock.json + npm ci Pinned
Pipeline library @Library('[email protected]') Pinned
Company configuration Managed files with a stable ID Versioned in Jenkins (and in the backup from 05-03)
Jenkins plugins plugins.txt from 05-04 Pinned

For pom.xml itself to reject builds with unsuitable tools, Maven offers the Enforcer plugin, which can require, for example, a minimum Java and Maven version and fail with a clear message if they are not met (the requireJavaVersion and requireMavenVersion rules). It is a useful safety net when a project is built in varied environments.

Common Mistakes and Tips

  • mvn: command not found after copying an example from the Internet: the agent does not have Maven installed, and it should not; use ./mvnw.
  • ./mvnw: Permission denied: the script does not have execute permission in Git. Fix it with git update-index --chmod=+x mvnw, as in 01-04.
  • Forgetting the quotes in -s "$MAVEN_SETTINGS": it works until the workspace path contains a space.
  • Interpolating MAVEN_SETTINGS with Groovy ("-s ${MAVEN_SETTINGS}"): it fails with No such property, because it is a shell environment variable, not a Groovy one. In the library it is escaped with \$.
  • Copying the managed settings.xml into the repositories "to test locally": as soon as it contains credentials, they will end up in Git. Developers have their own ~/.m2/settings.xml.
  • Replacing npm ci with npm install because "npm ci fails": it hides an outdated lockfile and breaks reproducibility.
  • Enabling the Gradle daemon on shared agents without measuring: memory used between builds and failures that are hard to reproduce.
  • Tip: when you change a managed file, treat it like any platform change: note it in the Comment field and let the teams know. Unlike code, Jenkins does not keep a version history of managed files; the JENKINS_HOME backup is your only way to recover the previous content.

Exercises

Exercise 1. Create the maven-settings-tecnoshop managed file, release tecnoshop-lib v1.2.0 with the settings parameter and its test, and update orders-api. In the console of the main build, find the path of the temporary file and check, with docker compose exec linux-agent-01 ls, that it no longer exists when the build finishes. Why is this behavior important?

Exercise 2. A catalog-web developer opens a PR that changes "jest": "^29.7.0" to "jest": "^30.0.0" in package.json, without touching package-lock.json. Describe what happens in the PR build, why it is the desired behavior and what the developer should do.

Exercise 3. An orders-api PR (from someone with write permission) adds a <repositories> block to pom.xml with https://repo.dubious-example.test/maven2/, from which a new dependency is downloaded. The PR is rejected in review and never merged. Explain what effect it may still have on main builds with the agent's current configuration, and which three measures reduce it.

Solutions

Solution 1. The console shows a line copy managed file [maven-settings-tecnoshop] to file:/home/jenkins/agent/workspace/orders-api_main@tmp/config...tmp for each Maven step and Deleting 1 temporary files when the block exits. After the build:

docker compose exec linux-agent-01 ls /home/jenkins/agent/workspace/orders-api_main@tmp/

The config...tmp file is not there (and, with cleanWs(), the directory may not even exist). It matters because, from 06-05 onward, that file will contain the Nexus publishing credentials: the fact that it only exists while the block lasts narrows the window in which another process on the agent could read it, and keeps it from being left behind in a workspace that is kept.

Solution 2. The PR build fails in the Test stage of all three cells, in npm ci, with an error saying that package.json and package-lock.json are not in sync. That is what we want: npm ci refuses to guess which version of Jest to install, so nothing different from what is locked in the repository is ever built. The developer should run npm install on their machine (which will resolve Jest 30 and update the lockfile), check that the tests pass, and push both files to the PR. With a major version change, they should also read the release notes for the new Jest version.

Solution 3. Even though the PR is not merged, its build ran on linux-agent-01 and downloaded the dependency (and potentially other versions of existing dependencies, if the dubious repository served them before Maven Central) into the shared cache /home/jenkins/agent/.m2/repository. A later main build that requests those same coordinates will find them in the cache and use them without downloading them again: code from a rejected PR can end up inside the main artifact. Measures: (1) a <mirrorOf>*</mirrorOf> mirror to the company Nexus in the managed settings (06-05), which makes Maven ignore the repositories declared in pom.xml and send everything through the controlled proxy; (2) separate the PR builds' cache from the main cache (a different directory or, better, ephemeral agents for PRs, module 8); (3) clean the agent's cache after detecting a case like this and review PRs with special attention to changes in <repositories> and <pluginRepositories>.

Conclusion

You now know how to integrate build tools into Jenkins with a platform mindset. Maven comes through the wrapper, with the version pinned in .mvn/wrapper/maven-wrapper.properties, instead of through a Tools installation; the company configuration lives in Jenkins thanks to Config File Provider, with the maven-settings-tecnoshop file and the npmrc-tecnoshop .npmrc, which are handed to the build with configFileProvider or with the configId of the nodejs step and disappear when it finishes; and tecnoshop-lib v1.2.0 lets mavenTecnoShop use the settings specified with MAVEN_SETTINGS_ID. You have evaluated withMaven and understand why TecnoShop prefers to publish explicitly, you know the risks of a shared dependency cache (concurrency, contamination, poisoning from PRs, growth), you know how to build with Gradle (wrapper, --no-daemon, build cache written only from main) and with npm (npm ci, cache on the volume, managed .npmrc), and how to invoke other tools with pinned versions. The builds already produce test and coverage results that, for now, can only be seen by reading the log. In the next lesson, Integrating with Testing Tools, you will turn them into reports, trends and thresholds that Jenkins understands.

© Copyright 2026. All rights reserved