Forked from ceilfors/cleanupUnusedWorkspaceInSlaves.groovy
Last active
September 9, 2024 13:25
-
-
Save bkrajendra/dccf64fd9efdc511c43f0a64a1499b88 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, Boolean dryRun) { | |
root.list().each { child -> | |
String fullName = path + child.name | |
if (isFolder(fullName)) { | |
deleteUnusedWorkspace(root.child(child.name), "$fullName/", dryRun) | |
} else { | |
if (Jenkins.instance.getItemByFullName(fullName) == null) { | |
println "Deleting: $fullName " | |
if (dryRun) { | |
// do nothing | |
} else { | |
child.deleteRecursive() | |
} | |
} | |
} | |
} | |
} | |
def cleanupWS(Boolean dryRun, String nodeType) { | |
if (nodeType == "s") { | |
for (node in Jenkins.instance.nodes) { | |
println "Processing $node.displayName" | |
def workspaceRoot = node.rootPath.child("workspace"); | |
deleteUnusedWorkspace(workspaceRoot, "", dryRun) | |
} | |
} else { | |
def masterWorkspaceRoot = Jenkins.instance.rootPath.child("workspace"); | |
deleteUnusedWorkspace(masterWorkspaceRoot, "", dryRun) | |
} | |
} | |
cleanupWS(true, "m") // cleanup master node, dry run | |
cleanupWS(true, "s") // cleanup all salve nodes, dry run |
Updated for cleaning up master node. added dryRun flag
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
need to test