Skip to content

Instantly share code, notes, and snippets.

@ceilfors
Last active September 14, 2023 20:30
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 18 You must be signed in to fork a gist
  • Save ceilfors/1400fd590632db1f51ca to your computer and use it in GitHub Desktop.
Save ceilfors/1400fd590632db1f51ca 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()
}
}
}
}
for (node in Jenkins.instance.nodes) {
println "Processing $node.displayName"
def workspaceRoot = node.rootPath.child("workspace");
deleteUnusedWorkspace(workspaceRoot, "")
}
@ceilfors
Copy link
Author

ceilfors commented Sep 6, 2023

Sorry I missed all previous comments. I haven't used Jenkins for a while. You can comment on the code that deletes the workspace and see what "println "Processing $node.displayName"" would print out before you proceed.

@pdharmendra
Copy link

Hi @ceilfors
I did the same and I see it prints the slave node name. Anyways, I would read some Jenkins scripting docs to find out about the master.
Thank you again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment