Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Sysa/9071f77347fbd81ba3ca0fcee4f0cedb to your computer and use it in GitHub Desktop.
Save Sysa/9071f77347fbd81ba3ca0fcee4f0cedb to your computer and use it in GitHub Desktop.
When you delete jobs in Jenkins, the corresponding workspaces in the build slaves won't be deleted automatically. This Jenkins script will go to each slave and check if the jobs are already deleted in Jenkins master and delete the workspace.
import com.cloudbees.hudson.plugins.folder.Folder
import hudson.FilePath
import jenkins.model.Jenkins
def boolean isFolder(String name) {
def item = Jenkins.instance.getItemByFullName(name)
return item instanceof Folder
}
def deleteUnusedWorkspace(FilePath root, String path) {
root.list().each { child ->
String fullName = path + child.name
if (isFolder(fullName)) {
deleteUnusedWorkspace(root.child(child.name), "$fullName/")
} else {
if (Jenkins.instance.getItemByFullName(fullName) == null) {
println "Deleting: $fullName "
//child.deleteRecursive()
echo $fullName
}
}
}
}
for (node in Jenkins.instance.nodes) {
println "Processing $node.displayName"
def workspaceRoot = node.rootPath.child("workspace");
deleteUnusedWorkspace(workspaceRoot, "")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment