Jenkins “Post-build Actions” allows you to define actions that should be taken after a build is completed. One of these actions is the “Post-build Failure Cleanup” action, which allows you to specify a set of files or directories that should be deleted if the build fails.
This can be useful to clean up any files or directories created as part of the build process and is no longer needed if the build fails. You can specify the files or directories to delete by entering a list of patterns and using wildcards to match the desired files.
In this tutorial, you will learn how to configure a post-failure cleanup build action in Jenkins.
Jenkins Post Block
The post block is a section of the Jenkinsfile that specifies a series of steps to be run after the main pipeline execution. It can perform cleanup tasks, send notifications, or perform other actions that should be run regardless of whether the pipeline was successful.
The post block can contain several blocks, including success, failure, unstable, changed, and always. Each of these blocks is executed depending on the outcome of the pipeline. For example, the failure block is executed if any stage of the pipeline fails and the success block is executed if all stages of the pipeline are successful.
We can use the post block to define the workspace cleanup action if a build has failed.
Example 1 – Basic Workspace Cleanup
The following pipeline shows how we can use the post block to define a clean-up action if a build fails.
agent any
stages {
stage('Build') {
steps {
sh ‘hello.sh’
}
}
}
post {
failure {
deleteDir()
}
}
}
This Jenkinsfile defines a pipeline with a single stage called “Build”. Inside the stage, you can put your build steps. The post block at the end of the file contains a failure block that will be executed if the pipeline stage fails. The deleteDir() function will delete the entire workspace, effectively cleaning it up.
Note that this Jenkinsfile will clean up the workspace on failure for all stages in the pipeline. If you want to clean up the workspace only for specific stages, you can specify multiple post blocks, one for each stage.
Example 2 – Cleanup Workspace on Each Stage
The following example pipeline demonstrates how you to define post-cleanup operation on each stage:
agent any
stages {
stage('Build') {
steps {
// build steps go here
}
}
stage('Test') {
steps {
// test steps go here
}
}
}
post {
failure {
// clean up workspace on failure of Build stage
deleteDir()
}
}
post {
failure {
// clean up workspace on failure of Test stage
deleteDir()
}
}
}
Conclusion
In this post, you discovered how you can use Jenkins post block and failure action to clean up the workspace if a build fails on a given stage.