Skip to content
Latchkey

How to Use post {} Conditions in a Jenkins Pipeline

The post {} block runs steps after a stage or pipeline based on outcome: always, success, failure, unstable, or changed.

Add post {} at the pipeline or stage level. Each condition (like failure or always) holds steps that run only when that outcome applies, ideal for cleanup and alerts.

Outcome-based post steps

Cleanup always runs; the failure notification only fires when the build fails.

Jenkinsfile
pipeline {
  agent any
  stages {
    stage('Build') {
      steps { sh 'npm ci && npm run build' }
    }
  }
  post {
    always {
      cleanWs()
    }
    success {
      echo 'Build succeeded'
    }
    failure {
      mail to: 'team@example.com',
           subject: "Failed: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
           body: "See ${env.BUILD_URL}"
    }
  }
}

Gotchas

  • always runs no matter what; put workspace cleanup and artifact archiving there.
  • changed runs only when the build result differs from the previous run, useful for status flips.
  • Stage-level post {} scopes to that stage; pipeline-level scopes to the whole run.

Key takeaways

  • post {} runs steps by outcome: always, success, failure, etc.
  • Put cleanup and archiving under always.
  • post can attach to a stage or the whole pipeline.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →