How to Clean the Workspace in a Jenkins Pipeline
cleanWs (from the Workspace Cleanup plugin) deletes the workspace so a build starts from a known-clean tree.
Call cleanWs() in a post block to clean after a build, or as the first step to clean before checkout. For a plain delete without the plugin, use deleteDir().
Steps
- Install the Workspace Cleanup plugin to get
cleanWs. - Call
cleanWs()inpost { always { } }to clean after every run. - Or call
deleteDir()at the start of a stage to clean before work.
Jenkinsfile
Jenkinsfile
pipeline {
agent any
stages {
stage('Build') {
steps {
deleteDir()
checkout scm
sh 'make build'
}
}
}
post {
always {
cleanWs(deleteDirs: true, patterns: [[pattern: 'dist/**', type: 'INCLUDE']])
}
}
}Gotchas
cleanWs()needs the Workspace Cleanup plugin;deleteDir()is built in.- Cleaning before checkout discards any cached dependencies in the workspace.
Related guides
How to Set the Build Display Name and Description in JenkinsRename a Jenkins build and set its description from the pipeline with currentBuild.displayName and currentBui…
How to Guard a Stage With fileExists in JenkinsRun a Jenkins step only when a file is present using the fileExists step inside a when expression or an if, s…