Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 40 ยท Pipeline as Code

Conditions and Post Actions

Control which Jenkins stages run with when (branch, expression, changeset, allOf, anyOf, not) and react to results with post blocks, build results and cleanup.

Two questions come up in almost every real pipeline. Should this stage run at all? (Deploy only on main; run the frontend tests only when frontend files changed.) And what should happen when the build ends? (Send a message on failure; always clean the workspace.) Declarative Pipeline answers the first with the when directive and the second with the post section.

Both depend on build results, so this lesson also explains the result states and how currentBuild.result changes. The real directives are shown read-only. Two JavaScript stand-ins evaluate when rules and post blocks so you can see exactly which ones fire.

When a stage runs

branch Match a branch name or pattern.
expression Any Groovy true or false.
changeset Only if matching files changed.
allOf / anyOf / not Combine conditions.
1 / 2

The when directive

when goes inside a stage. If its condition is false, the stage is skipped (shown grey in the stage view) and the pipeline continues with the next stage.

GROOVY
stage('Deploy') {
  when {
    branch 'main'
  }
  steps {
    sh './deploy.sh'
  }
}

Built-in conditions

  • branch 'main' matches the branch name. With a pattern: branch pattern: 'release-*', comparator: 'GLOB'. Branch conditions need a multibranch pipeline, because the BRANCH_NAME variable is set there.
  • environment name: 'DEPLOY_ENV', value: 'prod' matches an environment variable (see Environment Variables and Parameters).
  • expression { return params.RUN_SLOW_TESTS } runs any Groovy that returns true or false. It is the escape hatch for everything else.
  • changeset 'frontend/**' is true when the changes in this build touch files matching the pattern. It is the key to monorepo pipelines (see Project: A Monorepo Pipeline).
  • buildingTag() and tag 'v*' are for builds started from a Git tag.
  • triggeredBy 'TimerTrigger' distinguishes nightly builds from human ones.
  • not { ... }, allOf { ... } and anyOf { ... } combine conditions. A when block with several conditions side by side behaves like allOf.
GROOVY
stage('Publish') {
  when {
    allOf {
      branch 'main'
      not { changeRequest() }
      anyOf {
        environment name: 'RELEASE', value: 'true'
        triggeredBy 'TimerTrigger'
      }
    }
  }
  steps {
    sh './publish.sh'
  }
}

Here the stage runs only for main, never for a pull request (changeRequest() is true on those), and only when either RELEASE is true or a timer started the build.

beforeAgent

By default Jenkins allocates the stage's agent first and evaluates when afterwards. If the stage is going to be skipped, you have wasted time waiting for an agent (or a Docker container start-up). Add beforeAgent true to evaluate the condition on the controller first:

GROOVY
stage('Deploy') {
  agent { label 'deployer' }
  when {
    beforeAgent true
    branch 'main'
  }
  steps { sh './deploy.sh' }
}

beforeInput true and beforeOptions true do the same before an input or options directive.

Build results

At any moment a build has a result. The values, from best to worst, are:

  1. SUCCESS: nothing went wrong.
  2. UNSTABLE: the pipeline ran to the end, but something such as failing tests marked it unstable.
  3. FAILURE: a step failed.
  4. NOT_BUILT: the build did not run its work (for example, a stage-level condition left nothing to do).
  5. ABORTED: someone stopped the build, or a timeout fired.

The result only ever gets worse as a build goes on. In currentBuild.result, an unset value (null) means "so far, so good", which Jenkins treats as SUCCESS at the end. You can set it yourself:

GROOVY
script {
  if (readFile('report.txt').contains('WARN')) {
    currentBuild.result = 'UNSTABLE'
  }
}

currentBuild.currentResult is the live value including pending state, and currentBuild.previousBuild?.result is the result of the previous build, which is how Jenkins decides whether a build "changed" (below).

The post section

post holds blocks that run after the stages (or after one stage, if placed inside it). Each block has a condition name:

Condition Runs when
always Every time
success The result is SUCCESS
failure The result is FAILURE
unstable The result is UNSTABLE
aborted The result is ABORTED
unsuccessful Anything that is not SUCCESS
changed The result differs from the previous build's
fixed This build succeeded and the previous one did not
regression This build is worse than the previous one
cleanup Last of all, after every other block, whatever happened
GROOVY
post {
  always {
    junit 'reports/*.xml'
  }
  failure {
    echo 'Build failed. Posting to the team channel...'
  }
  fixed {
    echo 'Back to green.'
  }
  cleanup {
    cleanWs()
  }
}

Some details worth knowing:

  • Several blocks can fire for one build. A failure after a green build triggers always, changed, regression, failure and unsuccessful, and then cleanup.
  • The blocks run in a fixed order: always, changed, fixed, regression, aborted, failure, success, unstable, unsuccessful, and cleanup last. Do not rely on the order between conditions for anything important.
  • cleanup always runs, even when other post blocks fail. Put workspace cleaning and similar tidying there. (cleanWs() is a step from the Workspace Cleanup plugin.)
  • A pipeline-level post runs on the pipeline's agent. With agent none at the top, steps that need a workspace in a pipeline-level post fail, so wrap them in node { } or move the post into a stage that has an agent.
  • A stage-level post runs when that stage ends, before later stages, which makes it a fine place for per-stage notifications or to publish that stage's test report.

Model: evaluating when

The first stand-in is a mini when evaluator. Conditions are JavaScript objects that mirror the real ones. It evaluates a pipeline's stages against a build context and prints which run.

JS A stand-in when evaluator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A pull request on a feature branch skips Publish because branch 'main' is false. The release branch skips both test stages because no files changed, which is how a monorepo avoids rebuilding everything.

Model: results and post blocks

The second stand-in tracks the result of a build as stages run, finds the previous result, and decides which post blocks fire, in the documented order.

JS A stand-in for results and post

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the "Tests failed" scenario Deploy never runs (the loop stops at the first failure), but always, changed, regression, failure, unsuccessful and cleanup all do. In "Fixed", changed and fixed fire together, which is why teams use fixed for "back to green" messages and failure for "it broke".

Common mistakes

  • Using post { failure } to clean up. If the build is aborted or unstable, it does not run. Use always or cleanup.
  • Forgetting beforeAgent true and holding an expensive agent for a stage that skips.
  • Testing branch conditions in a plain (non-multibranch) pipeline, where BRANCH_NAME is not set.
  • Writing complex Groovy inside expression. Move it into a script or a shared library function.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A stage's when condition is false. What happens?

    A false when skips just that stage, shown grey, and the next stage runs normally.
  2. 2. Which post condition runs only when this build succeeds and the previous one did not?

    fixed means back to green after a failure or unstable build. changed would also fire for a regression.
  3. 3. Which post block is guaranteed to run last?

    cleanup runs after every other post condition has been handled, so it is the safe place for tidying up.
  4. 4. What does beforeAgent true do in a when block?

    It avoids waiting for (or starting) an agent for a stage that will be skipped anyway.

Summary

  • when goes inside a stage; a false condition skips only that stage.
  • Use branch, environment, expression, changeset, buildingTag, triggeredBy, and combine them with not, allOf and anyOf.
  • Add beforeAgent true to avoid wasting an agent on skipped stages.
  • Results are SUCCESS, UNSTABLE, FAILURE, NOT_BUILT and ABORTED, and only get worse during a run.
  • post blocks react to the result; always and cleanup run regardless, and fixed and regression compare with the previous build.

Finally, learn the older, more flexible style of writing pipelines in Scripted Pipeline and Groovy for Jenkins.