Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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, "")
}
@devops04cloud

This comment has been minimized.

Copy link

commented Aug 11, 2018

Hey from where do we run this script, and how to run. Im new to devops, plz help.

@oarmstrong

This comment has been minimized.

Copy link

commented Oct 23, 2018

Thanks a lot for this! 👍

@tastewind

This comment has been minimized.

Copy link

commented Feb 21, 2019

Hey from where do we run this script, and how to run. Im new to devops, plz help.
Run this script in "Script Console".

@SUDARSHANCHAUDHARI

This comment has been minimized.

Copy link

commented May 31, 2019

@devops04cloud and @tastewind,

Open Jenkins >> Manage Jenkins

then scroll down in the options list and look for "Script Console"

image

Hope this will help you!

Thank you

@kusumat

This comment has been minimized.

Copy link

commented Jun 4, 2019

Why isFolder is being considered instead of deleting directly if the path doesn't exist in jenkins master

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.