Deleting temporary workspace files within a Jenkins pipeline

Using deleteDir() from within a pipeline stage does not delete the @tmp, @script directories which get generated at run-time.

Over time, this leads to Jenkins pipelines taking up disk space across Jenkins slave nodes or worse case directly on the master; whether this is checked out code, built binaries etc..

To free up disk space, add the following to the post stage of a pipeline.

Here we are explicitly specifying the dir() with the workspace path to remove recursively.

Keeping deleteDir() ensures any other directory’s are also removed from the workspace.

post {
    always {
        deleteDir()
        dir("${env.WORKSPACE}@tmp") {
            deleteDir()
        }
        dir("${env.WORKSPACE}@script") {
            deleteDir()
        }
        dir("${env.WORKSPACE}@script@tmp") {
            deleteDir()
        }
    }
}
Last updated on 22 Jan 2020
Published on 22 Jan 2020