Jenkins workspaces can balloon to hundreds of gigabytes, impacting disk space and build times.

Here’s how to keep them tidy:

The Problem: Disk Space and Build Time

Jenkins jobs, by default, keep all files and directories from previous builds within the job’s workspace on the Jenkins controller or agent. This accumulation can quickly consume significant disk space, leading to performance degradation and, eventually, out-of-space errors. Furthermore, a large workspace can dramatically increase the time it takes for a job to start, as Jenkins needs to scan and manage all those files.

The Solution: Post-Build Cleanup

The most effective way to manage Jenkins workspace size is to configure jobs to clean up after themselves. This isn’t about deleting build artifacts (those should be archived separately if needed), but rather removing the transient files and directories that are only necessary during a build.

How to Implement Cleanup

There are several ways to achieve this, ranging from simple job configuration to more advanced scripting.

  1. Using Jenkins’ Built-in Cleanup Options:

    • "Delete previous build’s workspace before build starts": This is the simplest and often most effective method.

      • Diagnosis: Navigate to your Jenkins job’s configuration page. Under the "Build Environment" section, look for the option "Delete workspace before build starts."
      • Fix: Check this box.
      • Why it works: Jenkins will completely remove the job’s workspace directory on the agent before executing any build steps. This ensures a clean slate for every build, preventing any leftover files from previous runs from accumulating.
      • Caveat: This deletes everything in the workspace, so ensure any artifacts you need are archived in the job’s post-build actions.
    • "Discard old builds": While not directly cleaning the workspace, this action reduces the number of build records and their associated artifacts/logs, which also consume disk space.

      • Diagnosis: In the job configuration, under the "Post-build Actions" section, you’ll find "Discard old builds."
      • Fix: Configure this to keep a specific number of builds (e.g., "Keep a maximum of 10 builds") or to retain builds for a certain number of days (e.g., "Days to keep builds: 7").
      • Why it works: Jenkins periodically prunes build records that exceed these limits, freeing up disk space and improving performance by reducing the number of build history entries.
  2. Using cleanWs() in Pipeline Jobs:

    For Jenkins Pipeline jobs (defined in Jenkinsfile), you can use the cleanWs() step.

    • Diagnosis: In your Jenkinsfile, if you don’t see explicit workspace cleanup, it’s likely accumulating.
    • Fix: Add cleanWs() to your post section, or at the beginning of your stages.
      pipeline {
          agent any
          stages {
              stage('Build') {
                  steps {
                      // Your build steps here
                      echo "Building..."
                  }
              }
          }
          post {
              always {
                  cleanWs() // Cleans the workspace after every build, regardless of success or failure
              }
          }
      }
      
      Or, to clean before the build:
      pipeline {
          agent any
          stages {
              stage('Checkout and Cleanup') {
                  steps {
                      cleanWs() // Cleans the workspace before checking out code
                      checkout scm
                  }
              }
              stage('Build') {
                  steps {
                      echo "Building..."
                  }
              }
          }
      }
      
    • Why it works: cleanWs() is a built-in Pipeline step that performs a full workspace cleanup, similar to the "Delete workspace before build starts" option in Freestyle jobs. Placing it in the post { always { ... } } block ensures it runs even if the build fails.
  3. Custom Scripting with deleteDir or Shell Commands:

    If you need more granular control over what gets deleted, you can use custom shell scripts or Jenkins Pipeline steps.

    • Diagnosis: Your workspace is growing, and you need to preserve certain directories (e.g., downloaded dependencies that are expensive to re-download) while cleaning others.
    • Fix (Freestyle Job): In the "Build" steps, add an "Execute shell" or "Execute Windows batch command" step.
      # Example: Delete all except a specific directory
      rm -rf *  # Delete everything
      mv /path/to/your/preserved_directory . # Move it back (or recreate if needed)
      
      Or, more safely, delete specific unwanted directories:
      # Example: Delete build output directories
      rm -rf build/ target/ dist/
      
    • Fix (Pipeline Job): Use the sh or bat steps.
      stage('Cleanup') {
          steps {
              sh 'rm -rf build/ target/ dist/' // Example for Linux/macOS agents
              // For Windows agents:
              // bat 'rd /s /q build\\ target\\ dist\\'
          }
      }
      
      Alternatively, use the deleteDir step for more controlled deletion within a Pipeline:
      stage('Cleanup') {
          steps {
              deleteDir() // Deletes the entire workspace
              // Or to delete specific files/directories:
              // deleteDir(includes: 'build/**, target/**, dist/**')
          }
      }
      
    • Why it works: These commands allow you to precisely define which files or directories are removed from the workspace, giving you fine-grained control over the cleanup process. deleteDir is Jenkins-native and handles file deletion reliably across different operating systems.

Best Practices

  • Archive Artifacts Separately: Never rely on the workspace to store build artifacts you might need later. Use the "Archive the artifacts" post-build action.
  • Understand Your Needs: If you have build tools that heavily rely on the workspace structure or require cached dependencies, you might need a more nuanced cleanup strategy than a full delete. However, for most typical CI/CD workflows, a complete workspace wipe is ideal.
  • Monitor Disk Space: Regularly check the disk space on your Jenkins agents, especially if you have many jobs or long-running builds.

The next issue you’ll likely encounter after implementing workspace cleanup is managing the size of your Jenkins build logs, which can also grow considerably over time.

Want structured learning?

Take the full Jenkins course →