At the end of module 3, the orders-api Jenkinsfile already builds, tests, packages, archives the jar and simulates a deployment to dev, all with flow control and error handling. But it is still a flat list of four stages sharing a single workspace, and in Developing and Debugging Pipelines you saw one of the consequences: Restart from Stage fails if the chosen stage needs files generated by an earlier stage. In this lesson you will get to know in depth the building blocks of more elaborate pipelines: how to group stages by nesting them, how to assign an agent per stage, how to pass files from one stage to another with stash/unstash (and keep them for Restart from Stage), and the catalog of steps you will use every day to read and write files, run commands with fine-grained control, wait, retry, trigger other jobs and coordinate builds. By the end, orders-api will generate a build-info.txt file with the build's traceability data and will have a Smoke stage that actually starts the jar and checks that it responds.
Starting Point and Goals
Laura reviews the module 3 Jenkinsfile with Diego and Marta, and they write down three needs:
- Traceability: when someone downloads an archived jar, there is no easy way to know which commit it comes from. They want a
build-info.txtfile, archived next to the jar, with the version, the commit, the build number and the URL. - A real smoke check: in 02-02 the
orders-api-smokejob only checked that the jar existed and was in ZIP format. Marta wants to start the application and check that it responds. - Rerunning without rebuilding: if the smoke stage fails for a transient reason, they want to use Restart from Stage without the jar going missing.
All three are solved with what you will see in this lesson. Parallel execution, environment variables in depth and manual approvals are covered in 04-02, 04-03 and 07-03.
Nested Sequential Stages: Grouping Stages
A stage can contain exactly one of these four things:
stage content |
What it means | Where it is covered |
|---|---|---|
steps { } |
Steps that run in order | Module 3 |
stages { } |
Child stages that run in sequence | This lesson |
parallel { } |
Child stages that run at the same time | 04-02 |
matrix { } |
The same stages repeated for each combination of values | 04-02 |
With stages inside a stage you can group related stages:
pipeline {
agent any
stages {
stage('Build and test') {
stages {
stage('Build') {
steps {
sh './mvnw -B clean compile'
}
}
stage('Tests') {
steps {
sh './mvnw -B test'
}
}
}
}
stage('Delivery') {
when {
expression { params.ENVIRONMENT == 'dev' }
}
stages {
stage('Package') {
steps {
sh './mvnw -B -DskipTests package'
}
}
stage('Deploy to dev') {
steps {
echo 'Deployment SIMULATION'
}
}
}
}
}
}stage('Build and test') { stages { ... } }: a "container" stage with nostepsof its own. Its childrenBuildandTestsrun one after the other.- The point of grouping is that the parent stage's directives apply to all its children: the
whenofDeliverydecides in one go whetherPackageandDeploy to devrun. The same goes foragent,environment,options(for example, a commontimeoutfor the group),toolsandpost. - In Pipeline Graph View the group is drawn as a block that contains its children; in the old Stage View, on the other hand, only the "leaf" stages appear, without the grouping.
When to Group and When Not To
| Group if... | Do not group if... |
|---|---|
Several stages share a when condition, an agent or a timeout |
You only want to "tidy up visually" a short pipeline |
You want a common post for a block (for example, to clean up a test environment) |
You need to use Restart from Stage on those stages |
The last row matters: Restart from Stage only lets you choose top-level stages. Nested stages do not appear in its drop-down list. That is why, in orders-api, Laura decides to keep the main stages at the top level: the pipeline is short, and being able to rerun Smoke or Deploy to dev is worth more than the grouping.
Per-Stage agent and Global agent none
You already saw in Pipeline Syntax that each stage can declare its own agent. Let's review what that implies, because it is the whole reason stash exists:
pipeline {
agent none
stages {
stage('Build') {
agent any
steps {
sh './mvnw -B clean package -DskipTests'
}
}
stage('Check') {
agent any
steps {
sh 'ls -l target/' // will the jar be here?
}
}
}
}agent noneat the root: the pipeline does not reserve any executor globally. It only takes one while a stage with anagentis running.- Each stage-level
agent anyrequests a new executor (which may be on another node), creates or reuses a workspace and does its own implicit checkout. - Consequence: the
target/fromBuilddoes not necessarily exist inCheck. Even on a single node, if the first workspace is still busy, Jenkins may assignorders-api-pipeline@2.
| Approach | Advantages | Drawbacks |
|---|---|---|
Global agent any (or label) |
One shared workspace; stages see the files from earlier ones | One executor is held for the whole build, even while waiting |
agent none + per-stage agent |
Each stage uses the right node (Linux, Windows, Docker...); no executor is held while waiting | Each stage does its own checkout and files must be passed explicitly |
Today, with only the built-in node and its two executors, agent none adds nothing to orders-api and introduces redundant checkouts; that is why we keep the global agent any. Its real value will show up when there are agents with different labels in Managing Jenkins Nodes and Agents and ephemeral agents with Docker and Kubernetes in module 8. What we will set up right now is the correct way to move files between stages, because it will work exactly the same on the day each stage runs on a different node.
Passing Files Between Stages: stash and unstash
stash saves a set of files from the workspace on the controller, tied to the current build, under a name. unstash restores them into the workspace where it runs, whether that is the same node or any other.
name: 'jar': the stash identifier. It is unique within the build; if you reuse the name, the second stash replaces the first.includes: 'target/*.jar': an Ant-style pattern (as inarchiveArtifacts) relative to the current directory. You can specify several, separated by commas.unstash 'jar': restores the files with the same relative path they had (target/orders-api-1.0.0-SNAPSHOT.jar) in the current directory.
stash parameters:
| Parameter | Default value | What it is for |
|---|---|---|
name |
(required) | Stash identifier |
includes |
The whole directory | Which files to save |
excludes |
Nothing | Which of the included files to discard |
useDefaultExcludes |
true |
Excludes control files such as .git/** |
allowEmpty |
false |
If false, fails when there are no files to save |
An example with excludes, saving the target directory but without the test reports:
stash vs. archiveArtifacts
stash / unstash |
archiveArtifacts |
|
|---|---|---|
| Purpose | Passing files within the same build | Keeping files for people and other jobs |
| Visibility | Does not appear in the interface | Appears on the build page and can be downloaded |
| Lifetime | Deleted when the build finishes (unless preserveStashes) |
According to the retention policy (buildDiscarder) |
| Retrieval | Only with unstash in the same build |
Download, Copy Artifact, REST API |
Size Limits
Stashes are compressed into a .tar.gz and sent to the controller, which stores them in $JENKINS_HOME/jobs/<job>/builds/<number>/stashes/. They are meant for small files: a jar of a few dozen megabytes, scripts, reports. There is no hard limit, but stashing hundreds of megabytes (a node_modules, a Maven repository, disk images) puts a load on the controller's network, CPU and disk, and slows down every build in the installation. For large files, the alternative is an external artifact repository, which you will see in Artifact and Image Repositories.
preserveStashes() and Restart from Stage
By default, stashes are deleted when the build finishes. That is exactly what broke Restart from Stage: the new build skips the earlier stages and, with the cleanWs() in cleanup, the workspace arrives empty. The preserveStashes option keeps the stashes of the most recent finished builds so that a restart can use them:
buildCount: 5: keeps the stashes of the 5 most recent builds. Without a parameter,preserveStashes()keeps only those of the last one. The maximum is 50.- When you use Restart from Stage, the new build inherits the stashes of the original build, so an
unstash 'jar'in the restarted stage finds the exact jar that was generated back then.
flowchart LR
subgraph B24["Build #24 (original)"]
E1["Package<br/>stash 'jar'"] --> H1["Smoke<br/>unstash 'jar'<br/>fails (port in use)"]
end
S[("Stash 'jar'<br/>kept by<br/>preserveStashes")]
E1 -.-> S
subgraph B25["Build #25 (Restart from Stage 'Smoke')"]
O["Build, Tests,<br/>Package skipped"] --> H2["Smoke<br/>unstash 'jar'<br/>OK"]
end
S -.-> H2
Notice that this only works because the restarted stage requests its files with unstash instead of assuming they are in the workspace. That is the rule of thumb: every stage that can be rerun on its own must retrieve what it needs.
File Steps: readFile, writeFile, fileExists, dir and deleteDir
These steps work in the agent's workspace, not on the controller, which is why they are the correct way to handle files from a pipeline (remember from 03-06 why you should not use java.io.File).
writeFile: creates or overwrites the file with the given text. If the path includes directories that do not exist, it creates them.
readFile: returns the contents as a string. Because it returns a value that you store in a variable, it is used insidescript. If the file does not exist, the step fails.
script {
if (fileExists('target/orders-api-1.0.0-SNAPSHOT.jar')) {
echo 'The jar is in the workspace'
} else {
error 'The jar is missing: was Package skipped?'
}
}fileExists: returnstrueorfalse. It works with files and with directories.
dir('smoke') { }: runs the steps in the block withsmoke/as the current directory (relative to the workspace). If it does not exist, it creates it.deleteDir(): deletes the current directory and everything in it. Insidedir('smoke')it deletes onlysmoke/; outside anydir, it deletes the entire workspace. Use it with care.
| Step | Returns a value? | Fails if the file does not exist? |
|---|---|---|
writeFile |
No | No (it creates it) |
readFile |
Yes (string) | Yes |
fileExists |
Yes (boolean) | No (returns false) |
dir |
No | No (creates the directory) |
deleteDir |
No | No |
deleteDir()vs.cleanWs(): both delete, butcleanWs()(Workspace Cleanup plugin) always acts on the whole workspace, supports patterns and handles deletion failures better. For the entire workspace, incleanup, we keep usingcleanWs(); for a subdirectory,dir(...) { deleteDir() }.
The sh Step in Depth: returnStatus, returnStdout and label
So far you have used sh in two ways: sh 'command' and, in 03-02, with returnStdout. Its default behavior is to fail if the command exits with a code other than 0. Its parameters change that:
| Parameter | Effect | Return value |
|---|---|---|
| (none) | Fails if the exit code is not 0 | Nothing |
returnStdout: true |
Captures standard output instead of displaying it | String (with the trailing newline) |
returnStatus: true |
Never fails because of the exit code | int (the exit code) |
label: 'text' |
Shows text instead of the script in the step views |
— |
encoding: 'UTF-8' |
Encoding used to read the output | — |
returnStdout and returnStatus cannot be combined: Jenkins reports an error if you specify both.
script {
def shortCommit = sh(script: 'git rev-parse --short HEAD', returnStdout: true, label: 'Short commit').trim()
def status = sh(script: 'grep -q "spring-boot-starter-actuator" pom.xml', returnStatus: true, label: 'Look for actuator in the pom')
if (status == 0) {
echo "Commit ${shortCommit}: the pom includes actuator"
} else {
unstable 'The pom does not include spring-boot-starter-actuator; the Smoke stage will not be able to check /actuator/health'
}
}.trim(): removes the trailing newline thatgitadds. Forgetting it is a classic: the variable holds"a1b2c3d\n"and breaks comparisons and file names.returnStatus: true:grep -qreturns 0 if it finds the text and 1 if it does not. WithoutreturnStatus, a 1 would make the stage fail; with it, you decide what to do.label: in Pipeline Graph View and in the build's step view you will see "Short commit" instead ofgit rev-parse --short HEAD. With long scripts, like the one in theSmokestage you will see later, it is the difference between a readable view and a wall of text.
On Windows agents, the equivalents are bat (for cmd.exe) and powershell (or pwsh for PowerShell 7), with the same returnStdout, returnStatus and label parameters. At TecnoShop all nodes will be Linux, so we will not use them.
Waiting and Retrying: sleep, waitUntil and retry
sleep
Pauses the pipeline. sleep 10 is equivalent to 10 seconds. Unlike sh 'sleep 10', the sleep step does not start any process on the agent.
waitUntil
Repeats its block until it returns true. Between attempts it waits an increasing amount of time: it starts at initialRecurrencePeriod milliseconds (250 by default) and keeps increasing it up to a maximum of 15 seconds. It must always go inside a timeout, because on its own it would wait forever:
timeout(time: 2, unit: 'MINUTES') {
waitUntil(initialRecurrencePeriod: 2000, quiet: true) {
script {
def code = sh(script: 'curl -sf https://nexus.tecnoshop.local/service/rest/v1/status', returnStatus: true)
return code == 0
}
}
}- The block must end by returning a boolean; that is why we use
scriptandreturn. curl -sf:-ssilences the progress bar and-fmakescurlreturn an error code if the HTTP response is 4xx or 5xx.quiet: true: prevents each retry from writing a line to the console.- This example is illustrative:
nexus.tecnoshop.localis fictitious and you will meet it in 06-05.
Important trap: Jenkins kills processes started in the background (
command &) when theshstep that started them finishes. That is why you cannot start the application in oneshand wait for it withwaitUntilin the next one: by the time it starts waiting, the application will already be dead. If you need to start something, wait for it and check it, do it in a singlesh, as in theSmokestage in this lesson.
retry
You already used it in 03-05: retry(3) { ... } repeats the block for up to 3 attempts. Its extended form accepts conditions to retry only on certain failures, for example when the connection to the agent is lost (retry(count: 2, conditions: [agent()]) { ... }), something that will make sense with ephemeral agents in module 8.
Triggering Other Jobs with build
The build step triggers another Jenkins job from a pipeline. It is the "in code" version of the Build other projects option you configured in 02-02, but much more powerful: it can pass parameters, wait for the result and decide what to do with it.
Marta's Job: orders-api-regression
Marta wants every orders-api build to eventually trigger her regression suite, which QA will maintain in its own job. For now she creates a practice job that simulates it. New Item → orders-api-regression → Pipeline → in Pipeline script:
pipeline {
agent any
options {
timeout(time: 5, unit: 'MINUTES')
}
parameters {
string(name: 'SOURCE_BUILD', defaultValue: 'manual', description: 'orders-api build that requests the regression run')
booleanParam(name: 'SIMULATE_FAILURE', defaultValue: false, description: 'For practice only: makes the regression run fail')
}
stages {
stage('Regression') {
steps {
echo "SIMULATION: QA regression requested by ${params.SOURCE_BUILD}"
sleep time: 5, unit: 'SECONDS'
script {
if (params.SIMULATE_FAILURE) {
error 'Simulated failure in the regression run'
}
}
}
}
}
}Save it and run it once with Build Now: as with any pipeline, the parameters are registered in the job after the first run.
Triggering It and Collecting Its Result
stage('QA regression') {
steps {
script {
def regression = build job: 'orders-api-regression',
parameters: [
string(name: 'SOURCE_BUILD', value: "${env.JOB_NAME} #${env.BUILD_NUMBER}"),
booleanParam(name: 'SIMULATE_FAILURE', value: false)
],
wait: true,
propagate: false
echo "Regression: build #${regression.number} finished with ${regression.result} (${regression.absoluteUrl})"
if (regression.result != 'SUCCESS') {
unstable "The QA regression run finished with ${regression.result}"
}
}
}
}job: 'orders-api-regression': the job name. If it were in a folder, it would be'folder/job'.parameters: [...]: each parameter with the type the target job declares (string,booleanParam,choice...). A parameter the target does not declare is ignored, with a warning in the console.wait: true(the default): waits for it to finish. Withwait: falseit triggers it and moves on; in that case there is no result to collect.propagate: false: the result of the triggered job is not carried over to this build automatically. Withpropagate: true(the default), if the regression run fails, this stage fails too.- The step returns an object with properties of the triggered build:
result('SUCCESS','UNSTABLE','FAILURE'...),number,absoluteUrlanddurationString, among others. - With
propagate: falseyou decide: here theorders-apibuild ends up UNSTABLE if the regression run is not green.
wait |
propagate |
Behavior |
|---|---|---|
true |
true |
Waits; if the target fails, this stage fails (the most common setup) |
true |
false |
Waits and lets you decide based on result |
false |
(not applicable) | Triggers and continues ("fire and forget") |
Two warnings:
- With
wait: true, the source build keeps holding its executor while it waits, and the target needs another one. With the built-in node's two executors it works; with only one, it would wait forever. - Laura decides not to add this stage to the
orders-apiJenkinsfilewhile the regression run is a simulation: it would add time without providing any information. It stays as practice (exercise 3), and orchestration between jobs will come back in module 7.
Coordinating Builds: lock and milestone
Two steps solve concurrency problems between builds that appear once pipelines start deploying. Understanding the idea is enough for now; you will use them for real in module 7.
lock (Lockable Resources plugin): guarantees that only one build at a time uses a shared resource, even if the builds belong to different jobs.
stage('Deploy to dev') {
options {
lock(resource: 'env-dev')
}
steps {
echo 'Only one build at a time deploys to dev'
}
}- If
env-devis held by another build (of this job or another one), this build waits in the stage until it is released.disableConcurrentBuilds()only prevents simultaneous builds of the same job;lockworks across jobs.
milestone (included with pipelines): marks a numbered checkpoint. When a newer build passes a milestone, older builds that have not passed it yet are aborted. It prevents an old, slow build from deploying after a new one:
stage('Deploy to dev') {
steps {
milestone(ordinal: 10)
echo 'If a newer build already passed this point, this one never gets here'
}
}Catalog of the Most Common Steps
| Step | What it is for | Plugin that provides it |
|---|---|---|
echo |
Writing a message to the console | Pipeline: Basic Steps |
sh / bat / powershell |
Running commands on the agent | Pipeline: Nodes and Processes |
dir |
Changing the current directory for a block | Pipeline: Basic Steps |
deleteDir |
Deleting the current directory | Pipeline: Basic Steps |
readFile / writeFile |
Reading and writing text files in the workspace | Pipeline: Basic Steps |
fileExists |
Checking whether a file or directory exists | Pipeline: Basic Steps |
stash / unstash |
Passing files between stages of the same build | Pipeline: Basic Steps |
archiveArtifacts |
Keeping files as build artifacts | Pipeline: Basic Steps |
sleep |
Pausing | Pipeline: Basic Steps |
waitUntil |
Repeating until a condition is met | Pipeline: Basic Steps |
retry / timeout |
Retrying / limiting the time of a block | Pipeline: Basic Steps |
error / unstable |
Failing / marking as unstable with a message | Pipeline: Basic Steps |
catchError / warnError |
Tolerating failures in a block | Pipeline: Basic Steps |
build |
Triggering another job | Pipeline: Build Step |
lock |
Reserving a shared resource | Lockable Resources |
milestone |
Aborting old builds overtaken by newer ones | Pipeline: Milestone Step |
cleanWs |
Cleaning the workspace | Workspace Cleanup |
checkout / git |
Downloading code | Pipeline: SCM Step / Git |
The full list for your installation is always available under Pipeline Syntax → Steps Reference, and the Snippet Generator produces the exact syntax for each one, as you saw in 03-06.
Applying It at TecnoShop: build-info.txt, a Jar Stash and a Smoke Stage
- Generate
build-info.txt in Package
build-info.txt in Package script {
def version = sh(script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
returnStdout: true, label: 'Read the version from the pom').trim()
def date = sh(script: 'date -u +%Y-%m-%dT%H:%M:%SZ', returnStdout: true, label: 'Build date').trim()
currentBuild.description = "orders-api ${version}"
def lines = [
'application=orders-api',
"version=${version}",
"commit=${env.GIT_COMMIT}",
"build=${env.BUILD_NUMBER}",
"job=${env.JOB_NAME}",
"date=${date}",
"url=${env.BUILD_URL}"
]
writeFile file: 'build-info.txt', text: lines.join('\n') + '\n'
}
archiveArtifacts artifacts: 'target/*.jar,build-info.txt', fingerprint: true
stash name: 'jar', includes: 'target/*.jar'label: bothshsteps will appear with a readable name in the step views.date -u +%Y-%m-%dT%H:%M:%SZ: the date in UTC in ISO 8601 format (for example,2026-11-28T09:15:02Z). It is obtained with a command on the agent instead of with Java classes on the controller.env.GIT_COMMIT,env.BUILD_NUMBER,env.JOB_NAME,env.BUILD_URL: variables Jenkins defines in every build; you will study them in depth in 04-03.lines.join('\n') + '\n': joins the lines with newlines. Building the text from a list avoids the indentation spaces that would creep in with a multi-line string.archiveArtifacts artifacts: 'target/*.jar,build-info.txt': two patterns separated by a comma (no spaces). Now, next to the jar, you can download its "ID card".stash name: 'jar': the jar becomes available to the following stages and, withpreserveStashes, to Restart from Stage.
The resulting file will look like this:
application=orders-api version=1.0.0-SNAPSHOT commit=4f2c9e1a7b3d5c6e8f9a0b1c2d3e4f5a6b7c8d9e build=31 job=orders-api-pipeline date=2026-11-28T09:15:02Z url=http://localhost:8080/job/orders-api-pipeline/31/
- The
Smoke Stage: Start the Jar and Check That It Responds
Smoke Stage: Start the Jar and Check That It Responds stage('Smoke') {
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=$((18090 + 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
'''
}
}
}Step-by-step explanation:
dir('smoke') { deleteDir() ... }: works in a clean subdirectory, as if it were the workspace of another node. That way we check the jar that travels in the stash, not the one left in the workspace'starget/.unstash 'jar': restoressmoke/target/orders-api-1.0.0-SNAPSHOT.jar.'''...''': a Groovy string with triple single quotes, without interpolation; the$characters reach the shell untouched.PORT=$((18090 + EXECUTOR_NUMBER)):EXECUTOR_NUMBERis the executor number (0 or 1 on the built-in node). That way, two simultaneous builds never use the same port; and we avoid 8081 in case something is already using it.java -jar ... &: starts the application in the background and saves its output tosmoke.log.$!is the PID of the process just started.trap '...' EXIT: whatever happens (success or error), the application is killed when the script exits. Besides, as you saw, Jenkins would kill the process when theshfinishes, but it is better not to rely on that.- The
forloop tries up to 30 times, every 2 seconds, to query/actuator/health(the endpoint added byspring-boot-starter-actuatorin 01-04). When it responds with"status":"UP", it checks that/api/ordersreturns some of the sample orders (SHIPPED) and exits successfully. - If it never responds, it prints the application log (essential for diagnosis) and exits with code 1, which makes the stage fail.
options { timeout(...) }: a safety cap in case something hangs.
Deploy to dev Retrieves the Jar
Deploy to dev Retrieves the Jar steps {
unstash 'jar'
echo 'SIMULATION: this is where target/orders-api-1.0.0-SNAPSHOT.jar would be deployed to dev (real deployment in 06-06 and 07-03).'
}Even though today the jar is already in the workspace, the unstash makes the stage self-sufficient: it will work with Restart from Stage and on the day it runs on another agent.
The Updated Jenkinsfile
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, and it is simulated.')
}
triggers {
cron('TZ=Europe/Madrid\nH 2 * * 1-5')
pollSCM('TZ=Europe/Madrid\nH/15 * * * *')
}
stages {
stage('Build') {
steps {
echo "Build ${env.BUILD_NUMBER} of ${env.JOB_NAME} | ENVIRONMENT=${params.ENVIRONMENT} | RUN_TESTS=${params.RUN_TESTS}"
sh './mvnw -B clean compile'
}
}
stage('Tests') {
when {
expression { params.RUN_TESTS }
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
sh './mvnw -B test'
}
post {
failure {
echo 'The tests failed: check the log of this stage (reports in target/surefire-reports).'
}
}
}
stage('Package') {
steps {
sh './mvnw -B -DskipTests package'
script {
def version = sh(script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
returnStdout: true, label: 'Read the version from the pom').trim()
def date = sh(script: 'date -u +%Y-%m-%dT%H:%M:%SZ', returnStdout: true, label: 'Build date').trim()
currentBuild.description = "orders-api ${version}"
def lines = [
'application=orders-api',
"version=${version}",
"commit=${env.GIT_COMMIT}",
"build=${env.BUILD_NUMBER}",
"job=${env.JOB_NAME}",
"date=${date}",
"url=${env.BUILD_URL}"
]
writeFile file: 'build-info.txt', text: lines.join('\n') + '\n'
}
archiveArtifacts artifacts: 'target/*.jar,build-info.txt', fingerprint: true
stash name: 'jar', includes: 'target/*.jar'
}
}
stage('Smoke') {
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=$((18090 + 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 {
expression { params.ENVIRONMENT == 'dev' }
expression { params.RUN_TESTS }
}
}
steps {
unstash 'jar'
echo 'SIMULATION: this is where target/orders-api-1.0.0-SNAPSHOT.jar would be deployed to dev (real deployment in 06-06 and 07-03).'
}
}
}
post {
success {
echo "OK: orders-api #${env.BUILD_NUMBER} built successfully."
}
unstable {
echo "WARNING: orders-api #${env.BUILD_NUMBER} is unstable."
}
failure {
echo "ERROR: orders-api #${env.BUILD_NUMBER} failed. Check the red stage."
}
fixed {
echo 'orders-api is back to green after an earlier failure.'
}
cleanup {
cleanWs()
}
}
}What is new compared with the end of module 3:
preserveStashes(buildCount: 5)inoptions.Packageuseslabelon itsshsteps, generatesbuild-info.txtwithwriteFile, archives it next to the jar and saves the jar withstash.- A new
Smokestage, which checks the stashed jar by actually starting it. Deploy to devretrieves the jar withunstash.
Commit ("Add build-info.txt, the jar stash and the Smoke stage"), push and run a build. Check on the build page that two files have been archived and open build-info.txt. Then try Restart from Stage from Smoke: the earlier stages will show as skipped and Smoke will work with the jar from the original build.
Common Mistakes and Tips
- Adding
stepsandstagesto the samestage: a validation error. A stage contains one ofsteps,stages,parallelormatrix. No such saved stash 'jar': theunstashruns in a build where thestashwas never done (becausePackagefailed or was skipped) or in a Restart from Stage of a build whose stashes are no longer kept. CheckpreserveStashes.No files included in stash 'jar': theincludespattern does not match anything (for example, because thestashruns inside a differentdir). Remember that paths are relative to the current directory.- Stashing large things (
node_modules,~/.m2): slows down the controller. Save only what is strictly necessary. - Forgetting
.trim()afterreturnStdout: the trailing newline breaks comparisons and names. - Combining
returnStdoutandreturnStatus: not allowed. waitUntilwithouttimeout: if the condition is never met, the build waits until the globaltimeout(or forever if there is none).- Starting a process with
&in oneshand using it in the next: Jenkins kills it when the firstshfinishes. Do everything in a single script. deleteDir()outside adir: deletes the entire workspace, including the checked-out code.- Tip: design each stage so that it requests what it needs (
unstash) instead of assuming it is there. That is the foundation of Restart from Stage and of distributed pipelines.
Exercises
Exercise 1. At the end of the Smoke stage (outside the dir), add a block that reads build-info.txt with readFile and prints its contents to the console, but only if the file exists; if it does not exist, it must mark the build as unstable with a clear message. Then run Restart from Stage from Smoke: what happens and why?
Exercise 2. The Smoke stage has failed in two different builds. In build #40, because someone wrote CANCELLED instead of SHIPPED in the /api/orders check. In build #41, because another process on the controller was using the executor's port at that moment. For each case, state what you would do: Restart from Stage, Replay or a new commit. Justify your answer.
Exercise 3. Temporarily add the QA regression stage from this lesson to the Jenkinsfile, after Smoke. Run a normal build and another one in which the regression run fails (change SIMULATE_FAILURE to true in the call). What state does each build of orders-api and orders-api-regression end up in? What would change with propagate: true? Remove the stage when you are done.
Solutions
Solution 1.
script {
if (fileExists('build-info.txt')) {
echo "Build information:\n${readFile('build-info.txt')}"
} else {
unstable 'build-info.txt does not exist in the workspace'
}
}In a normal build the contents are displayed. In a Restart from Stage from Smoke, Package is skipped, the workspace starts out empty (cleanWs() cleaned it) and build-info.txt is not there, because it was not saved in any stash: the build ends up UNSTABLE. This is the practical demonstration of the rule "each stage requests what it needs": for it to work, you would have to include build-info.txt in the stash (includes: 'target/*.jar,build-info.txt') or in a second stash. The jar, on the other hand, does arrive, thanks to unstash 'jar' and preserveStashes.
Solution 2.
- Build
#40(an error in theJenkinsfilecode): Restart from Stage is no use, because it reruns exactly the sameJenkinsfileas the original build andSmokewould look forCANCELLEDagain. You can use Replay to check the fix quickly (although it runs the full build, rebuilding everything), but the definitive solution is a new commit with the corrected text: if you only fix it in Replay, the next build will fail again. - Build
#41(an external, transient cause): here Restart from Stage fromSmokeis the ideal tool. The code is correct, the jar is kept thanks topreserveStashesandunstash 'jar', and you avoid building, testing and packaging all over again.
Rule of thumb: Restart from Stage to repeat stages that failed for reasons unrelated to the code; Replay to experiment; a commit to fix.
Solution 3. With SIMULATE_FAILURE=false, both builds finish with SUCCESS and the orders-api console shows the number and URL of the regression build. With SIMULATE_FAILURE=true, orders-api-regression finishes with FAILURE; because of propagate: false, the error is not carried over, and our if marks orders-api as UNSTABLE (yellow), running the unstable post block. With propagate: true, the QA regression stage would fail, the following stages would be skipped and the orders-api build would finish with FAILURE; in addition, the code after the build step would never run. Also watch the queue while it runs: the orders-api build holds one executor and the regression run the other.
Conclusion
You now know the internal structure of a declarative pipeline beyond a flat list of stages: you can nest stages with stages so they share when, agent, options or post (knowing that Restart from Stage only sees the top level), you understand what giving each stage its own agent with a global agent none implies, and you know how to pass files between stages with stash/unstash, keep them with preserveStashes and why they must be small. You have mastered the file steps (readFile, writeFile, fileExists, dir, deleteDir), the sh parameters (returnStdout, returnStatus, label), waiting with sleep and waitUntil, the build step for triggering other jobs and collecting their result, and the idea behind lock and milestone. orders-api now generates a traceable build-info.txt and checks its jar by starting it in the Smoke stage. However, all its stages still run one after the other, even though some of them do not depend on each other. In the next lesson, Parallel Execution and Matrices in Pipelines, you will learn to run them at the same time to shorten the feedback loop, and you will meet TecnoShop's second project, catalog-web.
