You now have the Jenkinsfile in the repository and you know why TecnoShop writes its pipelines in declarative syntax. But, to be honest, the current orders-api pipeline still does less than the orders-api-build Freestyle job: it does not archive the jar, it mixes compiling and packaging in the same stage and it drags along a leftover chmod. In this lesson you will build, step by step and over several commit → build iterations, the first "real" orders-api Jenkinsfile: three stages with clear responsibilities (Build, Tests and Package) and archiving of the jar with fingerprints. Along the way you will learn the Groovy fundamentals you need to write a Jenkinsfile without surprises (quotes, interpolation, escaping $), the basic steps sh, echo, archiveArtifacts, dir and pwd, how to read the result stage by stage and how to interpret a failure. By the end, the pipeline will replace the Freestyle job as the team's reference job.
Starting Point and Goal
This is the Jenkinsfile as it stood at the end of Declarative vs Scripted Pipelines:
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'chmod +x mvnw'
sh './mvnw -B -DskipTests package'
script {
def version = sh(
script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
returnStdout: true
).trim()
echo "Project version: ${version}"
currentBuild.description = "orders-api ${version}"
}
}
}
stage('Tests') {
steps {
sh './mvnw -B test'
}
}
}
}And this is what orders-api-build does (you configured it in module 2): a checkout of */main with Clean before checkout, ./mvnw -B verify, archiving of target/*.jar with a fingerprint, plus other options (parameters, triggers, timeout, retention) that you will migrate in the next lesson.
Today's goal is a pipeline with this flow:
flowchart LR
A["Declarative:<br/>Checkout SCM"] --> B["Build<br/>clean compile"]
B --> C["Tests<br/>test"]
C --> D["Package<br/>package + version<br/>+ archiveArtifacts"]
The Work Cycle: Edit, Commit, Push, Build
With the Jenkinsfile in the repository, every change follows this cycle:
- You edit the
Jenkinsfileon your computer. git add Jenkinsfileandgit commit -m "...".git push.- You run
orders-api-pipelinewith Build Now (or wait for a change to trigger it, once you configure triggers). - You check the result and go back to step 1 if needed.
It is a somewhat slow cycle for experimenting; in Developing and Debugging Pipelines you will learn to shorten it with Replay and the linter. For now, make one small change per iteration: if something fails, you will know what caused it.
Iteration 1: Three Stages with Clear Responsibilities
Right now the Build stage does too many things: it compiles, packages the jar and works out the version. If it fails, the stage view does not tell you whether the problem is in compilation or in packaging. Let's split the responsibilities:
| Stage | Command | Responsibility |
|---|---|---|
Build |
./mvnw -B clean compile |
Start from scratch and check that the code compiles |
Tests |
./mvnw -B test |
Compile the tests and run them |
Package |
./mvnw -B -DskipTests package |
Generate the jar (the tests have already run) and record the version |
Replace the contents of the Jenkinsfile with:
pipeline {
agent any
stages {
stage('Build') {
steps {
sh './mvnw -B clean compile'
}
}
stage('Tests') {
steps {
sh './mvnw -B test'
}
}
stage('Package') {
steps {
sh './mvnw -B -DskipTests package'
script {
def version = sh(
script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
returnStdout: true
).trim()
currentBuild.description = "orders-api ${version}"
}
}
}
}
}What has changed and why:
sh 'chmod +x mvnw'is gone. In The Course Project you recorded the execute permission ofmvnwin Git withgit update-index --chmod=+x mvnw, so the checkout already leaves it executable. That step was redundant../mvnw -B clean compile:cleandeletes thetarget/directory before compiling. It plays the role that Clean before checkout played in the Freestyle job: every build starts from a clean state, with no stale classes from previous builds.compileonly compiles the main code; it does not reach the test phase, so-DskipTestsis not needed../mvnw -B test: Maven runs through the phases up totest. It detects that the main classes are already compiled and does not recompile them; it compiles the tests and runs them../mvnw -B -DskipTests package: generates the jar. We use-DskipTestsbecause the tests have already run in the previous stage; repeating them would only make the build longer. This is safe precisely because, if the tests fail, the pipeline stops and never reachesPackage.- The version
scriptblock moves toPackage: the version is a property of the artifact, so it fits better in the stage that produces it. We drop theechobecause the build description already shows it. -B(batch mode) on every invocation: avoids colors and progress bars that clutter the Jenkins console.
Push the change and start a build:
The stage view will now show four columns: Declarative: Checkout SCM, Build, Tests and Package, all green.
Iteration 2: Archiving the Jar
The jar is generated, but it will disappear as soon as the workspace is reused or deleted. Just as you did with Archive the artifacts in Workspaces, Artifacts and Build History, you need to archive it. In a pipeline you use the archiveArtifacts step. Add it at the end of Package:
stage('Package') {
steps {
sh './mvnw -B -DskipTests package'
script {
def version = sh(
script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
returnStdout: true
).trim()
currentBuild.description = "orders-api ${version}"
}
archiveArtifacts artifacts: 'target/*.jar', fingerprint: true
}
}archiveArtifacts: copies the specified files from the workspace to the build directory on the controller, where they are kept.artifacts: 'target/*.jar': the file pattern, the same one the Freestyle job used. It capturesorders-api-1.0.0-SNAPSHOT.jar(Spring Boot also leaves a.jar.original, which this pattern does not include).fingerprint: true: records the jar's MD5 fingerprint so it can be tracked, exactly like the Freestyle checkbox.
Commit ("Archive the jar with a fingerprint"), push and build. The build page will show Build Artifacts with the jar, and the stage console will show:
If the pattern does not match any file, archiveArtifacts makes the build fail with a message such as No artifacts found that match the file pattern "target/*.jar". That is the desired behavior: a build that does not produce its artifact is not a correct build. There is an allowEmptyArchive: true parameter for cases where the absence of files is normal, but ours is not one of them.
Groovy Fundamentals for Writing a Jenkinsfile
Before adding more steps, you need to master a handful of Groovy rules. Almost all beginner mistakes in a Jenkinsfile come from here.
Single and Double Quotes
| Syntax | Type | Interprets ${...}? |
Example | Result |
|---|---|---|---|---|
'...' |
Literal string | No | 'Build ${env.BUILD_NUMBER}' |
Build ${env.BUILD_NUMBER} (as is) |
"..." |
GString (interpolated string) | Yes | "Build ${env.BUILD_NUMBER}" |
Build 12 |
'''...''' |
Multi-line literal | No | Multi-line scripts | The text as is |
"""...""" |
Multi-line interpolated | Yes | Multi-line scripts with Groovy values | The text with values substituted |
Interpolation means replacing ${expression} with its value in Groovy, before the text goes anywhere:
echo 'Build ${env.BUILD_NUMBER}' // Prints: Build ${env.BUILD_NUMBER}
echo "Build ${env.BUILD_NUMBER}" // Prints: Build 12envis a global variable holding the build's environment variables;env.BUILD_NUMBERis the build number. Environment variables are covered in depth in Using Environment Variables.
Who Substitutes the $: Groovy or the Shell?
This is the most important subtlety. Inside an sh step, the $ can be interpreted by Groovy (when building the string) or by bash (when running the command):
- Single quotes in Groovy: the string reaches the shell as is, and it is bash that replaces
$BUILD_NUMBERand$HOMEwith the process's environment variables. This works, because Jenkins exportsBUILD_NUMBERas an environment variable.
- Double quotes in Groovy: Groovy substitutes
${env.BUILD_NUMBER}before running anything. \$HOME: the backslash escapes the$so that Groovy leaves it alone and it reaches bash as$HOME. Without the backslash, Groovy would look for a Groovy variable calledHOME, would not find it and the build would fail with an error such asNo such property: HOME.\": escapes the double quotes we want to pass to bash, because the Groovy string is also delimited by double quotes.
TecnoShop's rule of thumb:
- Use single quotes by default in
sh. It is more readable and avoids surprises. - Use double quotes only when you need a Groovy value (
params, adefvariable...), and escape with\$anything bash should interpret. - Never interpolate secrets with double quotes; you will see why in Credentials and Secrets Management.
Multi-Line Scripts
For several related commands, triple quotes save you from chaining lots of sh steps:
sh '''
echo "Contents of target:"
ls -lh target/*.jar
JAR=target/orders-api-1.0.0-SNAPSHOT.jar
echo "Size in bytes: $(stat -c %s "$JAR")"
''''''...''': since they are single quotes, Groovy touches nothing;$JARand$(...)are interpreted by bash.- The whole block runs in a single shell process, which is why the
JARvariable defined on one line is available on the next. By contrast, two separateshsteps are two independent processes: a variable defined in the first does not exist in the second. - Jenkins runs scripts with the
-xoption (prints each command before running it) and-e(stops at the first command that fails), unless the script starts with its own#!line.
Comments
// Single-line Groovy comment
/* Multi-line
Groovy comment */
sh '''
# This is a bash comment, inside the script
./mvnw -B -q validate
'''Outside scripts you use Groovy comments (// and /* */); inside an sh script, bash comments (#).
Calling Steps: Parentheses and Named Arguments
In Groovy, parentheses are optional in many calls. These two lines are equivalent:
And named arguments (name: value) are grouped into a map:
archiveArtifacts artifacts: 'target/*.jar', fingerprint: true
archiveArtifacts(artifacts: 'target/*.jar', fingerprint: true)Parentheses become mandatory when you use the value the step returns, as in def version = sh(script: ..., returnStdout: true).trim().
The Basic Steps: sh, echo, archiveArtifacts, dir and pwd
| Step | What it does | Where it runs | Example |
|---|---|---|---|
sh |
Runs a shell script; fails if the exit code is not 0 | On the allocated node (agent), by launching a process | sh './mvnw -B test' |
echo |
Writes a message to the console | On the controller, without launching any process | echo "Build ${env.BUILD_NUMBER}" |
archiveArtifacts |
Keeps workspace files on the controller | Reads from the workspace and stores on the controller | archiveArtifacts artifacts: 'target/*.jar', fingerprint: true |
dir |
Runs the steps in its block in a subdirectory of the workspace (creating it if needed) | — | dir('target') { sh 'ls -lh' } |
pwd |
Returns the path of the current directory | — | echo "Workspace: ${pwd()}" |
echo vs. sh 'echo ...'
They look the same, but they are not:
In the console:
- The
echostep writes directly to the log, does not launch any process on the agent and is instantaneous. Use it for informational messages. sh 'echo ...'launches a shell on the agent just to print some text: slower, and with an extra+line. Use it only if you need bash to compute the text (for example, with$(date)).
dir and pwd
pwd()returns the working directory; at the start, the workspace root (/var/jenkins_home/workspace/orders-api-pipeline).dir('target') { ... }: all the steps in the block run insidetarget/, as if you had donecd target. When the block ends, you return to the previous directory.- Why not
sh 'cd target && ls'? It would work for a singlesh, butdiraffects all the steps in the block (includingarchiveArtifactsorpwd) and makes the intent clear.
Iteration 3: Useful Information in the Console
Add a message at the beginning of Build that identifies the build. It is a very useful practice when you go through old consoles:
stage('Build') {
steps {
echo "Build ${env.BUILD_NUMBER} of ${env.JOB_NAME}"
sh './mvnw -B clean compile'
}
}- Double quotes, because we want Groovy to substitute
env.BUILD_NUMBERandenv.JOB_NAME(the job name).
After this iteration, the Jenkinsfile looks like this:
pipeline {
agent any
stages {
stage('Build') {
steps {
echo "Build ${env.BUILD_NUMBER} of ${env.JOB_NAME}"
sh './mvnw -B clean compile'
}
}
stage('Tests') {
steps {
sh './mvnw -B test'
}
}
stage('Package') {
steps {
sh './mvnw -B -DskipTests package'
script {
def version = sh(
script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
returnStdout: true
).trim()
currentBuild.description = "orders-api ${version}"
}
archiveArtifacts artifacts: 'target/*.jar', fingerprint: true
}
}
}
}Commit ("Identify the build in the console"), push and build.
Reading the Result Stage by Stage
Open the build and check the result in the three available views:
- Stage View (job page): one row per build and one column per stage, with the duration of each. With several builds you will see the average per stage and spot any stage that is getting slower.
- Pipeline Graph View (the pipeline graph link on the build page): the stages as connected nodes. Clicking a stage shows its steps and the log of each one.
- Console Output: the full console, where each stage starts with
[Pipeline] { (Name)and ends with[Pipeline] // stage.
An excerpt from the console of the Package stage:
[Pipeline] stage
[Pipeline] { (Package)
[Pipeline] sh
+ ./mvnw -B -DskipTests package
[INFO] Scanning for projects...
...
[INFO] Tests are skipped.
...
[INFO] Building jar: /var/jenkins_home/workspace/orders-api-pipeline/target/orders-api-1.0.0-SNAPSHOT.jar
...
[INFO] BUILD SUCCESS
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ ./mvnw -q help:evaluate -Dexpression=project.version -DforceStdout
[Pipeline] }
[Pipeline] // script
[Pipeline] archiveArtifacts
Archiving artifacts
Recording fingerprints
[Pipeline] }
[Pipeline] // stageWhen you are tracking down a problem, always start with the graph view to identify the stage, and then open only that stage's log.
Iteration 4: Triggering a Failure in Tests
Let's see how the pipeline reacts to a failure. In OrderControllerTest, change the expected value 3 to 4 in listReturnsThreeOrders:
Commit and push ("Deliberately broken test") and start the build. The result:
| Stage | Status | Why |
|---|---|---|
Declarative: Checkout SCM |
Green | The code downloads without problems |
Build |
Green | The main code compiles |
Tests |
Red | ./mvnw -B test returns a non-zero exit code |
Package |
Skipped (gray) | It does not run after a failure |
In the console:
[Pipeline] { (Tests)
[Pipeline] sh
+ ./mvnw -B test
...
[ERROR] OrderControllerTest.listReturnsThreeOrders:18 expected: <4> but was: <3>
[ERROR] Tests run: 3, Failures: 1, Errors: 0, Skipped: 0
...
[INFO] BUILD FAILURE
...
script returned exit code 1
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Package)
Stage "Package" skipped due to earlier failure(s)
[Pipeline] }
[Pipeline] // stage
...
ERROR: script returned exit code 1
Finished: FAILUREWhat you should take away from this:
script returned exit code 1: theshstep failed because Maven returned 1. That is the link between "the command fails" and "the stage fails".Stage "Package" skipped due to earlier failure(s): in a declarative pipeline, after a failure, the remaining stages are skipped and recorded as such, instead of disappearing.- No jar is archived: this build has no Build Artifacts. A jar with broken tests never becomes available, which is exactly what we want.
- The final result is
Finished: FAILURE, and the build description has not been set, because thescriptblock is inPackage.
Restore the test (put 3 back), commit and push, and start a build: everything should be green again. Later on you will learn to react to failures with post and to handle errors without stopping the pipeline (03-05), and to publish test results with trend charts using the junit step (06-03).
Freestyle vs. Pipeline: TecnoShop's Decision
| Capability | orders-api-build (Freestyle) |
orders-api-pipeline (today) |
|---|---|---|
| Definition | Forms in the interface | Jenkinsfile versioned in orders-api |
| Checkout | SCM section + Clean before checkout | Implicit checkout + Maven clean |
| Build and tests | A single ./mvnw -B verify |
Separate Build and Tests stages |
| Locating a failure | Read the whole console | Red stage and per-stage log |
| Archiving | Archive the artifacts with fingerprint | archiveArtifacts with fingerprint: true |
| Version in the history | No | orders-api 1.0.0-SNAPSHOT description |
RUN_TESTS and ENVIRONMENT parameters |
Yes | Pending (03-04) |
| Nightly build and polling | Yes | Pending (03-04) |
| Timeout, timestamps, retention | Yes | Pending (03-04) |
| Review of process changes | No | Yes, through pull requests |
Laura and Diego go over it together and make the call: orders-api-pipeline becomes the reference job for orders-api. From now on, any improvement to the process will be made in the Jenkinsfile. The orders-api-build Freestyle job (and its orders-api-smoke) stays around temporarily as a safety net, until the pipeline has everything it still lacks; in the next lesson you will migrate those pieces and disable their triggers so there are no duplicate builds.
Common Mistakes and Tips
No such property: HOME(or any bash variable): you used double quotes inshand Groovy is trying to substitute$HOME. Use single quotes or escape it with\$HOME.echoprints${env.BUILD_NUMBER}literally: you used single quotes where you needed double quotes.- Variables that "disappear" between two
shsteps: eachshis a separate process. Group the commands in a singlesh '''...'''. No artifacts found that match the file pattern: the pattern does not match (for example,target/*.waror an absolute path).archiveArtifactspaths are relative to the workspace.- Running the tests twice:
packagewithout-DskipTestsaftertestrepeats all the tests. With a lot of tests, the build takes twice as long. - Many changes in a single commit: if the build fails, you will not know which one is to blame. Iterate in small steps.
- Tip: stage names are part of the pipeline's "interface". Change them as little as possible: Stage View groups its statistics by name, and a rename breaks the comparison with earlier builds.
Exercises
Exercise 1. Predict what each line prints and check it in a build (you can add them temporarily at the end of Package and remove them afterward):
echo 'A: ${env.JOB_NAME}'
echo "B: ${env.JOB_NAME}"
sh 'echo "C: $JOB_NAME"'
sh "echo \"D: ${env.JOB_NAME} in \$HOME\""Exercise 2. In the Package stage, just before archiveArtifacts, add a check that, from inside target (using dir), shows the size of the jar and makes the stage fail if the jar is empty. Use a single multi-line sh step.
Exercise 3. Break the compilation (for example, remove a semicolon in OrderController.java), push the change and run the pipeline. Which stages run, which fail and which are skipped? How does this differ from the failure in iteration 4? Restore the code when you are done.
Solutions
Solution 1.
A: ${env.JOB_NAME}
B: orders-api-pipeline
+ echo C: orders-api-pipeline
C: orders-api-pipeline
+ echo D: orders-api-pipeline in /var/jenkins_home
D: orders-api-pipeline in /var/jenkins_home- A: single quotes, no interpolation: the literal text is printed.
- B: double quotes: Groovy substitutes the value.
- C: single quotes in Groovy; it is bash that substitutes
$JOB_NAME, an environment variable exported by Jenkins. The+line appears because it is a shell process. - D: Groovy substitutes
${env.JOB_NAME};\$HOMEreaches bash as$HOME, which in the controller container is/var/jenkins_home.
Solution 2.
dir('target') {
sh '''
JAR=orders-api-1.0.0-SNAPSHOT.jar
test -s "$JAR"
ls -lh "$JAR"
'''
}
archiveArtifacts artifacts: 'target/*.jar', fingerprint: truedir('target'): the script runs insidetarget/, which is why the jar path has no prefix.test -s "$JAR": returns a non-zero exit code if the file does not exist or is empty; since the script runs with-e, the stage fails at that point.archiveArtifactsstays outside thedirblock, so its pattern is still relative to the workspace root (target/*.jar). If you moved it inside, you would have to write*.jar.
Solution 3. Declarative: Checkout SCM runs (green) and Build fails (red), with a Maven error such as COMPILATION ERROR ... ';' expected that points to the file and line. Tests and Package are skipped (skipped due to earlier failure(s)). The difference from iteration 4 is that the stage view tells you, without opening the console, that the problem is in compilation and not in the tests: that is exactly the benefit of splitting responsibilities into stages. With the Freestyle job's ./mvnw -B verify, both failures would look the same: a red build that you have to read from start to finish.
Conclusion
You have built the first "real" orders-api Jenkinsfile in four commit → build iterations: the Build stage (clean compile), Tests (test) and Package (package without repeating the tests, the version in the description and archiveArtifacts with a fingerprint). You have mastered the Groovy rules that cause the most errors: single vs. double quotes, interpolation with ${...}, escaping with \$ so that bash interprets it, and multi-line scripts with '''. You know the sh, echo, archiveArtifacts, dir and pwd steps, you can read the result stage by stage and you have seen how a failure in Tests stops the pipeline, skips Package and prevents a faulty jar from being archived. The pipeline is now the reference job, but it still lacks the parameters, triggers, timeout, timestamps and retention that the Freestyle job had in the interface. To bring them into the Jenkinsfile, you need to know all the sections and directives of a declarative pipeline: that is the topic of Pipeline Syntax: Sections and Directives.
