At the end of the previous lesson, the orders-api Jenkinsfile already declared the RUN_TESTS and ENVIRONMENT parameters, but neither of them decided anything: the tests always ran and the environment only showed up in a message. On top of that, the pipeline did not react in any special way to a failure: it simply stopped. A real pipeline needs to decide which stages to run depending on the context, react to the result (warn if it fails, celebrate a recovery, always clean up) and handle errors with some nuance: not every failure should stop the build. In this lesson you will learn the three tools that make this possible in a declarative pipeline: the when directive, the post section and the error handling steps (error, unstable, catchError, warnError, retry, timeout and try/catch inside script). By the end you will have the complete orders-api Jenkinsfile that closes module 3.
The when Directive
when goes inside a stage and contains one or more conditions. If they are met, the stage runs; if not, it is skipped and the pipeline moves on to the next one.
when { ... }: the stage's block of conditions.expression { params.RUN_TESTS }: a condition written in Groovy. The block must returntrueorfalse; here it returns the parameter value directly, which, as you saw in 03-04, is a real boolean.- If there are several conditions inside
when, all of them must be met (an implicit "and").
when is a clear improvement over an if inside a script block: the decision is visible in the structure, it is validated before running and the skipped stage shows up as such in the interface.
when Conditions
| Condition | Met when... | Example | Notes |
|---|---|---|---|
expression |
The Groovy block returns true |
expression { params.ENVIRONMENT == 'dev' } |
The most flexible |
environment |
An environment variable has a given value | environment name: 'ENVIRONMENT', value: 'dev' |
Parameters are environment variables too |
equals |
Two values are equal | equals expected: 'dev', actual: params.ENVIRONMENT |
More readable than expression for comparisons |
branch |
The branch being built matches a pattern | branch 'main' |
Requires BRANCH_NAME, which multibranch pipelines provide (04-05) |
buildingTag |
A Git tag is being built | buildingTag() |
Multibranch with tag discovery |
tag |
The tag being built matches a pattern | tag 'v*' |
Same as the previous one |
changeset |
A file modified in this build matches the pattern | changeset 'src/**' |
Based on the build's new commits |
changeRequest |
The build corresponds to a pull request | changeRequest() |
Multibranch (04-05) |
triggeredBy |
The build was started by a specific cause | triggeredBy 'TimerTrigger' |
See the next table |
not |
The inner condition is not met | not { equals expected: 'production', actual: params.ENVIRONMENT } |
|
allOf |
All the inner conditions are met | allOf { ... ; ... } |
Logical "and" |
anyOf |
Any of the inner conditions is met | anyOf { ... ; ... } |
Logical "or" |
Common triggeredBy values:
| Value | Build cause | First console line |
|---|---|---|
'TimerTrigger' |
cron trigger |
Started by timer |
'SCMTrigger' |
pollSCM trigger |
Started by an SCM change |
'UserIdCause' |
A user started it by hand | Started by user ... |
cause: 'UserIdCause', detail: 'laura' |
A specific user | Started by user Laura Martin |
Three Warnings About Common Conditions
branchdoes not work inorders-api-pipeline: a regular Pipeline job does not defineBRANCH_NAME, sowhen { branch 'main' }is never met and the stage is always skipped. Use it once the job is multibranch.changesetdepends on history: in the first build, in one started bycronwith no new commits, or in a manual one with no changes, there are no modified files and the condition is not met. It is useful for monorepos, but not for deciding whether to run a service's tests.expressionis Groovy inside the sandbox: keep it short. If you need several lines of logic, that is a sign something should be solved another way.
Combining Conditions: not, allOf and anyOf
allOf: the stage runs only if the environment isdevand the tests have been run. (In practice this is equivalent to writing the two conditions directly inwhen, butallOfmakes the intent explicit and can be nested insideanyOfornot.)
anyOf: the stage runs in the nightly build or when Laura starts it by hand.
not: the stage runs in any environment exceptproduction.
When when Is Evaluated: beforeAgent and Friends
By default, if a stage declares its own options, input or agent, Jenkins processes them before evaluating when. That can be wasteful: a stage with its own agent could reserve an executor and do a full checkout only to find out afterward that it should not have run. Three modifiers change that order:
| Modifier | Effect |
|---|---|
beforeAgent true |
Evaluates when before allocating the stage's agent |
beforeInput true |
Evaluates when before requesting the stage's input |
beforeOptions true |
Evaluates when before applying the stage's options |
stage('Nightly report') {
agent any
when {
beforeAgent true
triggeredBy 'TimerTrigger'
}
steps {
echo 'Only in the nightly build'
}
}- With
beforeAgent true, in builds that are not nightly the stage is skipped without having taken up any executor. - In
orders-apithe agent is declared atpipelinelevel, so we do not need it yet; it will become important when stages have their own agents (module 8) or wait for approvals (07-03).
Applying It at TecnoShop: Optional Tests and a Simulated Deployment to dev
Laura defines two rules:
- The
Testsstage runs only ifRUN_TESTSis checked. - A
Deploy to devstage is added that, for now, simulates the deployment with anecho. It only runs if the chosen environment isdevand the tests have been run: an untested jar is never deployed, just as the parameter description warned. The real deployment will come in Integrating with Deployment Tools and Setting Up a CD Pipeline.
stage('Deploy to dev') {
when {
allOf {
expression { params.ENVIRONMENT == 'dev' }
expression { params.RUN_TESTS }
}
}
steps {
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).'
}
}params.ENVIRONMENT == 'dev': in Groovy,==compares the contents of two strings.- The stage goes after
Package: it only makes sense to deploy a jar that exists. - Keep in mind that automatic builds (
cronandpollSCM) use the default values (RUN_TESTS=true,ENVIRONMENT=dev), so every automatic build will "deploy" to dev. This is intentional:devis the environment where the team always wants to see the latest frommain.
What Skipped Stages Look Like
Start a build with Build with Parameters, unchecking RUN_TESTS and leaving ENVIRONMENT=dev. In the console:
[Pipeline] stage
[Pipeline] { (Tests)
Stage "Tests" skipped due to when conditional
[Pipeline] }
[Pipeline] // stage
...
[Pipeline] { (Deploy to dev)
Stage "Deploy to dev" skipped due to when conditionalskipped due to when conditional: the stage was skipped because itswhenwas not met. Compare it withskipped due to earlier failure(s), which you saw in 03-03 and which indicates a skip caused by an earlier failure.- In Stage View, skipped stages appear as a gray cell with no duration.
- In Pipeline Graph View, they are shown with a different style (dimmed, with a "skipped" icon), so they are clearly distinguishable from stages that failed or never got to run.
The build ends in SUCCESS: skipping stages because of a condition is not an error. That is why it matters that the echo in Build shows the parameters: whoever reads the build will know why the tests are missing.
The post Section
post defines actions that run when the pipeline or a stage finishes, depending on its result. It can go at two levels:
pipeline {
agent any
stages {
stage('Tests') {
steps {
sh './mvnw -B test'
}
post {
failure {
echo 'The tests failed' // STAGE post
}
}
}
}
post {
always {
echo 'End of build' // PIPELINE post
}
}
}- Stage
post: runs when that stage finishes, and its conditions refer to the result of the stage. - Pipeline
post: runs when all the stages have finished (or after the failure that stops the pipeline), and its conditions refer to the result of the build. - Each condition contains steps, just like
steps. - If a step inside
postfails, the build result is affected too; keeppostsimple.
post Conditions and Evaluation Order
| Condition | Runs when... | Typical use |
|---|---|---|
always |
Always, whatever the result | Publishing reports, logging the end of the build |
changed |
The result differs from the previous build's | Warning about any change of status |
fixed |
The current build is SUCCESS and the previous one was FAILURE or UNSTABLE | "Back to green" |
regression |
The current build is FAILURE, UNSTABLE or ABORTED and the previous one was SUCCESS | "Something broke" |
aborted |
The build was aborted (by hand or by a timeout) |
Recording the interruption |
failure |
The result is FAILURE | Warning about the failure |
success |
The result is SUCCESS | Success message |
unstable |
The result is UNSTABLE | Warning about failed tests or warnings |
unsuccessful |
The result is anything except SUCCESS | A single warning for everything that is not green |
cleanup |
Always, after all the other conditions | Cleaning the workspace and temporary resources |
Jenkins always evaluates the conditions in this order, regardless of the order in which you write them:
always → changed → fixed → regression → aborted → failure → success → unstable → unsuccessful → cleanup
Consequences of the order:
- In a build that recovers from a failure,
changed,fixedandsuccessrun, in that order (plusalwaysat the start andcleanupat the end). cleanupis the right place to delete things: it runs once all the other conditions (which may need files from the workspace) have finished.
Real team notifications (Slack #ci-orders, email to [email protected]) will be set up in Notifications and Team Feedback, and they will go precisely in these conditions. For now, we will use echo to hold their place.
post at TecnoShop: Messages and Cleanup with cleanWs()
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()
}
}success,unstable,failure: a different message for each result. In 06-07 you will replace them with notifications.fixed: the message a team appreciates most, because it closes an incident.cleanup { cleanWs() }: thecleanWs()step is provided by the Workspace Cleanup plugin, which you looked at in Using Jenkins Plugins. It deletes the workspace at the end of every build.
Why delete the workspace? On the built-in node, every workspace takes up the controller's disk; with cleanWs(), every build leaves the disk as it found it and the next one starts from scratch. The cost is that every build clones the repository again, which is negligible for a project the size of orders-api. Maven dependencies are not lost, because they are stored in the local repository ~/.m2, outside the workspace. We keep Maven's clean in Build in case a build is interrupted so abruptly that it never gets to run cleanup.
In addition, we add a stage post to Tests:
post {
failure {
echo 'The tests failed: check the log of this stage (reports in target/surefire-reports).'
}
}In Integrating with Testing Tools, this stage post is where the JUnit results will be published.
Handling Errors Inside Stages
By default, when a step fails, the stage fails, the following stages are skipped and the build ends in FAILURE. Often that is what you want. But not always: an optional report that fails should not bring down the build, and a transient network error deserves a second attempt. These are the steps available:
| Step | What it does | Result | Does the pipeline continue? |
|---|---|---|---|
error 'message' |
Triggers a failure with a clear message | FAILURE | No |
unstable 'message' |
Marks the build and the stage as unstable | UNSTABLE | Yes |
catchError(buildResult: ..., stageResult: ...) { } |
Catches a failure in the block and sets the given results | The ones you specify | Yes |
warnError('message') { } |
Catches a failure in the block and marks the build and stage as unstable | UNSTABLE | Yes |
retry(3) { } |
Repeats the block if it fails, up to 3 attempts in total | That of the last attempt | Depends on the last attempt |
timeout(time: ..., unit: ...) { } |
Aborts the block if it exceeds the time | ABORTED | No |
error: Failing with a Clear Message
script {
if (params.ENVIRONMENT == 'production' && !params.RUN_TESTS) {
error 'Preparing a build for production without running the tests is not allowed.'
}
}errorstops the build with the given message, without exception stack traces. It is the right way to abort a pipeline because of a condition you detect yourself, rather than ansh 'exit 1'.
unstable: Warning Without Stopping
- The build becomes UNSTABLE (yellow) and the pipeline continues. It is the status meant for "it works, but something needs checking". If you want later stages to be skipped once the build is already unstable, there is the
skipStagesAfterUnstable()option inoptions.
catchError and warnError: Failures That Should Not Stop the Build
Imagine Marta wants a report of outdated dependencies. It is useful, but it depends on the network and is not critical:
stage('Dependency report') {
steps {
catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE') {
sh './mvnw -B versions:display-dependency-updates'
}
}
}catchError { ... }: if something inside the block fails, the error is caught and the pipeline continues.buildResult: 'SUCCESS': the overall build result does not get worse.stageResult: 'UNSTABLE': the stage is marked as unstable, so the problem is visible in the stage view.- Always specify both parameters explicitly: that way, anyone reading the
Jenkinsfileknows exactly what happens on failure.
warnError is a shortcut for the most common case, "if it fails, make everything yellow":
retry and timeout as Steps
retry(3): if the dependency download fails (for example, because of a brief network outage), it is repeated until 3 attempts have been made. If the third one fails too, the error propagates.timeout(...)wrappingretry: limits the total time of all the attempts to 5 minutes. If it runs out, the build ends as ABORTED.- Do not use
retryto "fix" flaky tests: it hides the problem instead of solving it.
Remember the difference from 03-04: timeout and retry in options affect the whole pipeline or the whole stage; as steps, they only affect the block they wrap.
try/catch/finally Inside script
In a declarative pipeline, try/catch can only be used inside a script block. It makes sense when you need to do something with the error (for example, decide based on its message):
script {
try {
sh './mvnw -B versions:display-dependency-updates'
} catch (err) {
echo "Could not generate the report: ${err.getMessage()}"
unstable 'Dependency report not available'
} finally {
echo 'End of report attempt'
}
}try { }: the code that may fail.catch (err) { }: runs if it fails;erris the exception.finally { }: always runs, whether or not it failed.
Use it with caution: a catch that catches any error also catches build cancellation (if someone clicks abort while the sh is running, the cancellation exception gets "swallowed" and the build carries on). catchError and warnError handle that case correctly. TecnoShop's rule: post to react to the result, catchError/warnError for tolerable failures, try/catch only when there is no alternative.
currentBuild.result and currentBuild.currentResult
The currentBuild variable exposes the status of the current build:
| Property | Value while the build is going well | Value if something has worsened the result |
|---|---|---|
currentBuild.result |
null (not set yet) |
'UNSTABLE', 'FAILURE'... |
currentBuild.currentResult |
'SUCCESS' |
'UNSTABLE', 'FAILURE'... (never null) |
- Use
currentResultto read the result, because it is nevernull. - You can assign
currentBuild.result = 'UNSTABLE'insidescript, but the result can only get worse (you cannot go from FAILURE to SUCCESS). In a declarative pipeline, prefer theunstableanderrorsteps, which also leave a message in the console.
The Complete Flow
flowchart TD
A(["Start"]) --> B["Declarative: Checkout SCM"]
B --> C["Build"]
C --> D{"RUN_TESTS?"}
D -->|"yes"| E["Tests<br/>(stage post: failure)"]
D -->|"no"| E2["Tests skipped"]
E --> F["Package<br/>(version + archiveArtifacts)"]
E2 --> F
F --> G{"ENVIRONMENT == dev<br/>and RUN_TESTS?"}
G -->|"yes"| H["Deploy to dev<br/>(simulated)"]
G -->|"no"| H2["Deploy to dev skipped"]
H --> P["pipeline post:<br/>success / unstable / failure / fixed"]
H2 --> P
C -.->|"fails"| P
E -.->|"fails"| P
F -.->|"fails"| P
P --> L["cleanup: cleanWs()"]
L --> Z(["End"])
The dashed arrows show that, if a stage fails, the remaining ones are skipped and execution jumps straight to the pipeline's post section, which always runs.
The Jenkinsfile at the End of Module 3
This is the complete orders-api Jenkinsfile that closes the module. It is the starting point for module 4:
pipeline {
agent any
options {
timestamps()
timeout(time: 20, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
disableConcurrentBuilds()
}
parameters {
booleanParam(name: 'RUN_TESTS', defaultValue: true,
description: 'Uncheck only to quickly verify that 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
).trim()
currentBuild.description = "orders-api ${version}"
}
archiveArtifacts artifacts: 'target/*.jar', fingerprint: true
}
}
stage('Deploy to dev') {
when {
allOf {
expression { params.ENVIRONMENT == 'dev' }
expression { params.RUN_TESTS }
}
}
steps {
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 03-04:
wheninTests, which now honorsRUN_TESTS.- A stage
postinTests. - A new
Deploy to devstage, simulated and guarded withallOf. - A pipeline
postwith a message per result andcleanWs()incleanup. - The
ENVIRONMENTdescription is updated to reflect thatdevnow has a simulated deployment.
Commit ("Add flow control: when, post and simulated deployment to dev"), push and try three combinations with Build with Parameters: the default values (all stages green), RUN_TESTS unchecked (two stages skipped) and ENVIRONMENT=staging (only Deploy to dev is skipped).
Common Mistakes and Tips
when { branch 'main' }in a job that is not multibranch: the stage is always skipped, becauseBRANCH_NAMEdoes not exist.expression { params.RUN_TESTS == 'true' }: compares a boolean with a string and is always false. Useexpression { params.RUN_TESTS }.- An
ifinsidestepswithoutscript: a validation error. Usewhenor, if there is no other way,script { if ... }. - Putting
cleanWs()inalways:alwaysruns before the rest of the conditions, which might need files from the workspace. Cleanup goes incleanup. catchErrorwithout explicit parameters: it is easy to get confused about which result you end up with. Always specifybuildResultandstageResult.- A
try/catchthat swallows cancellation: the user clicks abort and the build keeps going. PrefercatchErrororwarnError. - Using
retryto hide flaky tests: the build comes out green, but the problem is still there. - Tip: a build with skipped stages should explain why. Showing the parameters at the start of the console, as
Builddoes, saves a lot of questions.
Exercises
Exercise 1. Add a Nightly report stage, after Deploy to dev, that runs only in builds started by the cron trigger and prints the message Nightly build completed with echo. How can you check that it works without waiting until 2 a.m.?
Exercise 2. For each case, state which pipeline post conditions run, and in what order, using the post from the TecnoShop section: (a) the previous build was SUCCESS and this one is SUCCESS; (b) the previous one was FAILURE and this one is SUCCESS; (c) the previous one was SUCCESS and this one is FAILURE.
Exercise 3. At the start of the Build stage, add a validation that makes the build fail, with a clear message, if ENVIRONMENT=production is chosen, because there is no production deployment yet. Then explain which post condition runs and what state the stages end up in.
Solutions
Solution 1.
stage('Nightly report') {
when {
triggeredBy 'TimerTrigger'
}
steps {
echo 'Nightly build completed'
}
}To test it without waiting, temporarily change the cron to fire soon (for example, TZ=Europe/Madrid\n*/5 * * * * so that it runs every 5 minutes), push, start a build by hand so that Jenkins registers the new trigger and wait for the next Started by timer build: in that one, the stage runs; in the manual ones you see skipped due to when conditional. Restore the original cron when you are done. In Developing and Debugging Pipelines you will see more convenient ways to run this kind of test.
Solution 2.
- (a)
successandcleanup. There is nofixed, because the previous build had not failed. - (b)
fixed,successandcleanup, in that order (the evaluation order putsfixedbeforesuccess). - (c)
failureandcleanup. If you had definedregression,changedorunsuccessful, they would run too, in the order shown in the table.
Solution 3.
stage('Build') {
steps {
echo "Build ${env.BUILD_NUMBER} of ${env.JOB_NAME} | ENVIRONMENT=${params.ENVIRONMENT} | RUN_TESTS=${params.RUN_TESTS}"
script {
if (params.ENVIRONMENT == 'production') {
error 'ENVIRONMENT=production is not supported yet: there is no production deployment.'
}
}
sh './mvnw -B clean compile'
}
}With ENVIRONMENT=production, the Build stage fails with the given message, without ever running Maven; the remaining stages appear as skipped due to earlier failure(s) and the build ends in FAILURE. In the pipeline post, failure (with the error message) and cleanup run. An alternative without script would be a Validate stage with when { equals expected: 'production', actual: params.ENVIRONMENT } and an error step in steps. Do not leave this validation in the course Jenkinsfile: the production deployment will be designed in module 7.
Conclusion
Your pipeline now decides, reacts and tolerates failures. With when and its conditions (expression, environment, equals, branch, changeset, triggeredBy, tag, combined with not, allOf and anyOf, plus the beforeAgent, beforeInput and beforeOptions modifiers), orders-api runs the tests only when RUN_TESTS says so and simulates a deployment to dev only with a tested jar. With post, at pipeline and stage level, it reacts to each result in a fixed evaluation order and cleans the workspace with cleanWs() in cleanup. And with error, unstable, catchError, warnError, retry, timeout and, as a last resort, try/catch inside script, you can decide which failures stop the build and which only mark it as unstable. The orders-api Jenkinsfile has reached its end-of-module-3 form. Now that it is more complex, every syntax or logic error costs a commit, push and build cycle. In the last lesson of the module, Developing and Debugging Pipelines: Replay, Snippet Generator and Linter, you will learn to shorten that cycle and to diagnose problems with the tools Jenkins puts at your disposal.
