0
0
Jenkinsdevops~5 mins

Workspace cleanup in Jenkins - Commands & Configuration

Choose your learning style9 modes available
Introduction
When Jenkins runs jobs, it stores files in a workspace folder. Over time, these files can pile up and cause storage issues or conflicts. Workspace cleanup removes old files to keep the environment clean and ready for new builds.
When you want to remove leftover files from previous builds to avoid conflicts.
When disk space on the Jenkins server is running low due to accumulated workspace files.
Before starting a new build to ensure a fresh environment without old artifacts.
After a build finishes to keep the workspace tidy and prevent clutter.
When troubleshooting build failures caused by stale or corrupted files in the workspace.
Commands
This command deletes all files and folders inside the workspace directory of the Jenkins job named 'example-job'. It is used to manually clean the workspace from the command line.
Terminal
rm -rf /var/lib/jenkins/workspace/example-job/*
Expected OutputExpected
No output (command runs silently)
-r - Recursively delete directories and their contents
-f - Force deletion without prompting for confirmation
This command uses Jenkins CLI to clean the workspace of the job 'example-job' remotely. It helps automate workspace cleanup without logging into the server.
Terminal
java -jar jenkins-cli.jar -s http://localhost:8080/ clean-workspace example-job
Expected OutputExpected
Workspace for job 'example-job' cleaned successfully.
This adds a post-build step in the Jenkins pipeline to always clean the workspace after the build finishes, ensuring no leftover files remain.
Terminal
echo 'post { always { cleanWs() } }' > Jenkinsfile
Expected OutputExpected
No output (command runs silently)
This command updates the Jenkins job configuration to include workspace cleanup steps defined in the job YAML file.
Terminal
jenkins-jobs --conf jenkins.ini update example-job.yaml
Expected OutputExpected
Job example-job updated successfully.
Key Concept

If you remember nothing else from workspace cleanup, remember: always remove old build files to keep Jenkins builds reliable and storage healthy.

Common Mistakes
Running rm command without the -r flag on directories
The command fails because rm cannot delete directories without -r.
Always include -r when deleting directories recursively.
Not cleaning workspace after builds
Old files accumulate and cause build conflicts or disk space issues.
Use cleanWs() in pipeline or manual cleanup steps after builds.
Deleting wrong workspace directory
Could delete important files or affect other jobs.
Double-check the workspace path before running cleanup commands.
Summary
Use rm -rf to manually delete workspace files from the Jenkins server.
Automate cleanup with Jenkins CLI or pipeline cleanWs() step.
Always clean workspace to prevent build errors and save disk space.