Skip to main content
In this tutorial, we’ll streamline a Jenkins Declarative Pipeline by moving multiple post { always { … } } blocks from individual stages into a single, pipeline-level post section. This approach enhances readability, reduces duplication, and makes future maintenance simpler.

Why Consolidate post { always } Blocks?

When you have several stages that each publish reports or perform cleanup, repeating the same post block can clutter your Jenkinsfile. Instead, you can leverage the pipeline-level post block to handle all “always” actions in one place.

Original Jenkinsfile with Repeated Post Sections

Below is a snippet of the existing pipeline. Notice the three stages that each contain their own post { always { … } } block:
We’re duplicating the same “always” publishing logic in three places. Let’s consolidate.

Consolidating Post Actions

Jenkins Declarative Pipeline allows a post section at the root of the pipeline block. All specified actions run after every stage completes.
The image shows a webpage from the Jenkins documentation, specifically focusing on "Pipeline Syntax." It includes a table of contents and sections on declarative pipelines.
For reference, check the official Jenkins Pipeline Syntax documentation.
A pipeline-level post block can contain always, success, failure, and unstable directives.

Post Actions Summary

Refactored Jenkinsfile

  1. Remove all individual post { always { … } } sections.
  2. Add one post block under the pipeline root.
  3. Copy each always step into that block.

Verifying the Refactor

After updating your Jenkinsfile, commit and push to trigger a new build:
In the Jenkins dashboard, you should see all post actions executed at the end of the pipeline:
The image shows a Jenkins dashboard with a list of projects, their last success and failure times, and build durations. The sidebar includes options like "New Item," "Build History," and "Manage Jenkins."
The image shows a Jenkins dashboard with build history in a stage view and graphs for code coverage and dependency-check trends. It includes details of various stages like checkout, build, tests, and deployment.
The image shows a Jenkins pipeline dashboard with a stage view of various build processes, including test results and execution times, along with a graph displaying vulnerability trends.

Next Steps

Jenkins pipelines can also leverage:
  • Environment directives for global variables
  • Parallel stages with failFast to optimize runtime
  • Embedded scripted logic (script { … }) for loops, conditionals, and error handling
Here’s a brief example showcasing parallel execution and a script block:

Watch Video

Practice Lab