Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paladin-dranser/6832f6726b0f608ebfee06a306cb8426 to your computer and use it in GitHub Desktop.
Save paladin-dranser/6832f6726b0f608ebfee06a306cb8426 to your computer and use it in GitHub Desktop.
Jenkins: Groovy script to clean up workspace on Jenkins agents
import hudson.model.*;
import hudson.util.*;
import jenkins.model.*;
import hudson.FilePath.FileCallable;
import hudson.slaves.OfflineCause;
import hudson.node_monitors.*;
void performCleanup(node, items) {
for (item in items) {
def jobName = item.getFullDisplayName()
println("Cleaning " + jobName)
if(item instanceof com.cloudbees.hudson.plugins.folder.AbstractFolder) {
performCleanup(node, item.items)
continue
}
if (item.isBuilding()) {
println(".. job " + jobName + " is currently running, skipped")
continue
}
println(".. wiping out workspaces of job " + jobName)
def workspacePath = node.getWorkspaceFor(item)
if (workspacePath == null) {
println(".... could not get workspace path")
continue
}
println(".... workspace = " + workspacePath)
def pathAsString = workspacePath.getRemote()
if (workspacePath.exists()) {
workspacePath.deleteRecursive()
println(".... deleted from location " + pathAsString)
} else {
println(".... nothing to delete at " + pathAsString)
}
}
}
for (node in Jenkins.instance.nodes) {
def computer = node.toComputer()
if (computer.getChannel() == null) {
continue
}
def rootPath = node.getRootPath()
def size = DiskSpaceMonitor.DESCRIPTOR.get(computer).size
int roundedSize = size / (1024 * 1024 * 1024)
println("node: " + node.getDisplayName() + ", free space: " + roundedSize + "GB")
computer.setTemporarilyOffline(true, new hudson.slaves.OfflineCause.ByCLI("disk cleanup"))
performCleanup(node, Jenkins.instance.items)
computer.setTemporarilyOffline(false, null)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment