147

How can I cleanup the workspace in Jenkins? I am using AccuRev as version control tool.

I created freestyle projects in Jenkins.

Promise Preston
  • 24,334
  • 12
  • 145
  • 143
Karthik
  • 1,471
  • 2
  • 9
  • 5

14 Answers14

129

There is a way to cleanup workspace in Jenkins. You can clean up the workspace before build or after build.

First, install Workspace Cleanup Plugin.

To clean up the workspace before build: Under Build Environment, check the box that says Delete workspace before build starts.

To clean up the workspace after the build: Under the heading Post-build Actions select Delete workspace when build is done from the Add Post-build Actions drop down menu.

Nagendra Singh
  • 1,361
  • 1
  • 7
  • 9
  • Thanks a lot Nagendra. I am able to fix this issue using workspace cleanup plugin. – Karthik Mar 04 '15 at 06:28
  • what will happen if i dont clean the workspace ? is it fetching the changes from the remote url or just building over same thing again and again? – alphaguy Jul 30 '19 at 11:20
  • @alphaguy Jenkins creates a new workspace for each build that you run, so if you don't delete the workspaces then eventually your node will run out of space. – Miles Winther Oct 16 '19 at 22:24
  • Can we reuse the workspace.. currently when i push the code it clone from git server then start the build. This takes a long process adding extra to build process! can we just pick the latest commit ? @MilesWinther – alphaguy Oct 17 '19 at 06:49
  • @alphaguy You can use a reference repo, see the answer here: https://stackoverflow.com/a/9932036/6221831 – Miles Winther Oct 17 '19 at 23:03
67

If you want to manually clean it up, for me with my version of jenkins (didn't appear to need an extra plugin installed, but who knows), there is a "workspace" link on the left column, click on your project, then on "workspace", then a "Wipe out current workspace" link appears beneath it on the left hand side column. screenshot

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
  • 7
    I don’t see that, unfortunately. Sure it is not a plugin? – Joachim Breitner Aug 27 '18 at 22:09
  • 3
    Hmm it seems that the "Workspace Cleanup Plugin" is indeed one of the plugins that is installed "by default." However, after removing it, I still have that link and it seems to still function. So...not sure where it comes from. V2.121.3 – rogerdpack Aug 28 '18 at 19:13
  • 2
    This worked but I had to click on the workspace link twice: the first one to go to the "workspace" page, the second time to actually show the "Wipe out current workspace" link. I guess it's an info you can include in the answer. – Gnafu Jan 31 '19 at 09:07
  • What Jenkins version is this one? Because mine does not show this option (probably mine is too old). – Pedro Trujillo Jul 29 '19 at 15:13
  • V2.121.3 not sure on other versions – rogerdpack Jul 29 '19 at 15:49
  • You can achieve the same result if you temporarily configure "Wipe out repository & force clone" in the Additional Behaviours section of your Job configuration. – Pait Jan 10 '20 at 14:54
  • 1
    2.319.1, this does not exist on a clean install. I would not trust "I removed the plugin and its still there". Also Workspace Cleanup Plugin is installed on my instance, this link does not exist in a single pipeline or multi-branch pipeline. – Dave Mar 03 '22 at 15:19
44

Workspace Cleanup Plugin

In Jenkins file add

cleanWs()

This will delete the workspace after the build is complete

Dave
  • 2,829
  • 3
  • 17
  • 44
waranlogesh
  • 874
  • 9
  • 11
  • 4
    I really appreciate this answer because I had the plugin installed from the other answers but this is what got it to work for my setup. Adding to that, I followed the links to the same plugin in the other answers, but `cleanWs()` wasn't present on the plugin landing page as syntax to add to my `Jenkinsfile`. – Arthur Weborg Feb 28 '19 at 22:46
41

Beside above solutions, there is a more "COMMON" way - directly delete the largest space consumer from Linux machine. You can follow the below steps:

  1. Login to Jenkins machine (Putty) enter image description here
  2. cd to the Jenkins installation path

Using ls -lart to list out hidden folder also, normally jenkin installation is placed in .jenkins/ folder

[xxxxx ~]$ ls -lart

drwxrwxr-x 12 xxxx  4096 Feb  8 02:08 .jenkins/
  1. list out the folders spaces

Use df -h to show Disk space in high level

du -sh ./*/ to list out total memory for each subfolder in current path.

du -a /etc/ | sort -n -r | head -n 10 will list top 10 directories eating disk space in /etc/

  1. Delete old build or other large size folder

Normally ./job/ folder or ./workspace/ folder can be the largest folder. Please go inside and delete base on you need (DO NOT delete entire folder).

rm -rf theFolderToDelete

enter image description here

Kevin
  • 1,335
  • 14
  • 14
  • 5
    Not sure why voted down. This sounds like a good option for Jenkins admins. Agree not for "read-only" users. – Saikat May 12 '17 at 16:12
  • 1. This doesn't really answer the question asked and 2. my Jenkins server is running on Windows. – mjaggard Jun 07 '17 at 09:15
  • 11
    @mjaggard The question was asked by some one else and he did not mention if it is for Windows only. Also he asked how to cleanup workspace (not limited to frontend/client). Am I missing anything obvious here? – Saikat Jun 08 '17 at 04:22
  • 5
    I totally agree with @takias, it seems a valid answer for the question. And a good one if you have enough permission to do it. – PhoneixS Jul 18 '17 at 14:54
  • 1
    This is an answer to "how do I recover space on a GNU/Linux machine" not jenkins specific. – Felipe Alvarez Jul 27 '18 at 06:31
  • 3
    I imagine this is the answer that my coworker found when he ran a script to delete any nested folders in the `/jobs/` directory. Problem is, if you have subfolders of jobs in Jenkins (like I did) the script will delete the JOB configuration, and not the build files. It wiped out multiple job configurations and we had to pull from backups to recreate them. ONLY use the UI/BuildDiscarder plugins and options to clean up the Master node. NEVER manually delete anything from the jobs folder. – KymikoLoco Sep 17 '21 at 22:23
36

IMPORTANT: It is safe to remove the workspace for a given Jenkins job as long as the job is not currently running!

NOTE: I am assuming your $JENKINS_HOME is set to the default: /var/jenkins_home.

Clean up one workspace

rm -rf /var/jenkins_home/workspaces/<workspace>

Clean up all workspaces

rm -rf /var/jenkins_home/workspaces/*

Clean up all workspaces with a few exceptions

This one uses grep to create a whitelist:

ls /var/jenkins_home/workspace \ 
  | grep -v -E '(job-to-skip|another-job-to-skip)$' \
  | xargs -I {} rm -rf /var/jenkins_home/workspace/{}

Clean up 10 largest workspaces

This one uses du and sort to list workspaces in order of largest to smallest. Then, it uses head to grab the first 10:

du -d 1 /var/jenkins_home/workspace \
  | sort -n -r \
  | head -n 10 \
  | xargs -I {} rm -rf /var/jenkins_home/workspace/{}
Sherwood Callaway
  • 1,428
  • 1
  • 14
  • 18
  • 11
    This is dangerous as jobs might be using those workspaces. – aleb May 14 '19 at 09:38
  • yikes... dont ever do this when using perforce, least not without some additional padding in your pipeline or you'll be in a world of hurt ! – Newtopian Oct 27 '21 at 19:31
  • 1
    I used `rm -rf /var/jenkins_home/workspaces/` after checking that no pipelines were executing (small team, I can disable build agents) to "fix" a git error causing a pipeline to fail. – iboisver Oct 27 '21 at 21:48
19

You can run the below script in the Manage JenkinsScripts Console for deleting the workspaces of all the jobs at one shot. We did this to clean up space on the file system.

import hudson.model.*
// For each project
for(item in Hudson.instance.items) {
  // check that job is not building
  if(!item.isBuilding()) {
    println("Wiping out workspace of job "+item.name)
    item.doDoWipeOutWorkspace()
  }
  else {
    println("Skipping job "+item.name+", currently building")
  }
}
mkobit
  • 43,979
  • 12
  • 156
  • 150
Upen
  • 1,388
  • 1
  • 22
  • 49
  • this does not work for me, it shows java.lang.NullPointerException: Cannot get property 'items' on null object . – Vincent Gerris Nov 28 '17 at 09:33
  • This script did nothing for me. It shows list of my projects with " Wiping out...", but doesn't clean anything. The workspace directory remains full. – Sergey Beloglazov Oct 08 '20 at 09:18
6

There is an option to do it. Configure -> Post-build Actions
The option comes by default at least in Jenkins version 2.236

5

If you want to just remove one dir (or file) you can use Groovy and Manage Jenkins → Scripts Console run a script which removes it.

For example, you can look at the files with:

dh = new File('./bitnami/jenkins/jenkins_home/workspace/jobname/folder')
dh.eachFile {
  println(it)
}

And then, when you have the folder you want to delete in dh, you could simply append the next code:

dh.deleteDir()

And it will be deleted.

Note: The path shown in the example is for a Bitnami Jenkins installation, yours could be different.

PhoneixS
  • 10,574
  • 6
  • 57
  • 73
4

not allowed to comment, therefore:

The answer from Upen works just fine, but not if you have Jenkins Pipeline Jobs mixed with Freestyle Jobs. There is no such Method as DoWipeWorkspace on Pipeline Jobs. So I modified the Script in order to skip those:

import hudson.model.*
import org.jenkinsci.plugins.workflow.job.WorkflowJob

// For each project
for(item in Hudson.instance.items) {
  // check that job is not building
  if(!item.isBuilding() && !(item instanceof WorkflowJob))
  {
    println("Wiping out workspace of job "+item.name)
    item.doDoWipeOutWorkspace()
  }
  else {
    println("Skipping job "+item.name+", currently building")
  }
}

you could also filter by Job Names if required: item.getDisplayName().toLowerCase().contains("release")

achschneid
  • 67
  • 7
4

Assuming the question is about cleaning the workspace of the current job, you can run:

test -n "$WORKSPACE" && rm -rf "$WORKSPACE"/*
aleb
  • 2,490
  • 1
  • 28
  • 46
2

You will need to install this plugin before the options mentioned above will appear

Workspace Cleanup Plugin

This plugin add the check box to all job configs to allow you to delete the whole workspace before any steps (inc source control) are run

This is useful to make sure you always start from a known point to guarantee how you build will run

Keir
  • 45
  • 5
  • 3
    Please add some information that your link is containing. Link-only answer are not what we are looking for at SO! :) – Chilion Feb 26 '15 at 08:26
  • 2
    This add's no more information that [this answer](https://stackoverflow.com/a/28728663/542251) hasn't already covered. In fact it add's a **lot** less – Liam Dec 14 '17 at 15:42
1

For those, who have builds within Docker under root user, following method may help:

def cleanupWorkspaceAsRoot() {
  log.notice "Removing workspace contents: $WORKSPACE !"
  docker.image('alpine').inside('-u root --env WORKSPACE') { // use docker instead of sudo // TODO make ALL docker builds work as non-ROOT, so there is no root-owned files
    sh 'test -n "$WORKSPACE" && rm -rf "$WORKSPACE"/*'
  }
}
1

if you are using Windows as your agent, you can use.

rmdir /s /q "folder path ending with \"

and if you are using linux machine as agent, you can use,

rm -rvf "directory"

But I wouldn't suggest this approach as it will create multiple chances of conflict and build failures.

Best approach is to use pipeline dependency. Create a main pipeline to delete the directory of the pipeline you want to delete and run the pipeline once delete is successful. You can use triggers to start the new build once delete is completed or vice versa to delete the directory once the build is completed.

pipeline {
    agent
    {
        node {
                label 'master'
                customWorkspace "${env.JobPath}"
              }
    }

    stages 
    {
        stage('Start') {
            steps {
                sh 'ls'
            }
        }

        stage ('Invoke_pipeline') {
            steps {
                build job: 'pipeline1', parameters: [
                string(name: 'param1', value: "value1")
                ]
            }
        }

        stage('End') {
            steps {
                sh 'ls'
            }
        }
    }
}

Code Source

https://www.jenkins.io/doc/pipeline/steps/pipeline-build-step/

Aniket Kumar
  • 165
  • 2
  • 10
0

If you are using docker, it might create files (from within docker container) that are not owned by user jenkins, and thus you need to use sudo to remove them:

    sh "sudo rm -rf \"$WORKSPACE\"/*"
    sh "sudo rm -rf \"$WORKSPACE\"/.*"

For this to work, you need to add /etc/sudoers -permission for user jenkins (please edit /etc/sudoers) e.g (these are full permissions without password):

jenkins ALL=(ALL) NOPASSWD: ALL
PHZ.fi-Pharazon
  • 1,479
  • 14
  • 15
  • 2
    If the `$WORKSPACE` variable gets empty for any reason, it is a recipe for a disaster: you'll get `sudo rm -rf /*` as a result. You could use it in this safer way: `"${WORKSPACE:?}"/*`. For `:?` explanation: https://stackoverflow.com/a/8889350/10788155 – Ictus Feb 21 '23 at 00:34