Skip to content
Latchkey

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() in post { 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

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