Last active
March 17, 2025 08:39
-
-
Save manavortex/0560f8afc982897cbd2693e9781f8e9c to your computer and use it in GitHub Desktop.
Jenkins: wipe workspace directory by job name
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
# call parametrized with string (JobName must be the fully-qualified name of your job) | |
# thanks to https://gist.github.com/dnozay/e7afcf7a7dd8f73a4e05 which was useful in figuring this out! | |
# works on 2.471.9 | |
import hudson.slaves.WorkspaceList | |
def job = null | |
try { | |
job = Jenkins.instance.getItemByFullName(env.JobName) | |
} catch (Exception e) { | |
println "Failed to get job ${env.JobName} - aborting" | |
throw e | |
} | |
def GetNodes() { | |
def nodes = [] | |
jenkins.model.Jenkins.instance.computers.each { c -> | |
nodes.add(c.node) | |
} | |
return nodes | |
} | |
def combinator = System.getProperty(WorkspaceList.class.getName(),"@"); | |
def CheckWorkspace(workspacePath) { | |
// stop checking (unlikely to have higher suffix) | |
if (!workspacePath.exists()) { | |
println " * ${workspacePath}: not found" | |
return false; | |
} | |
println " * found workspace: " + workspacePath.getRemote() | |
def targetDir = workspacePath.child('dist') | |
if (targetDir.exists()) { | |
if (!job.isBuilding()) { | |
println " * job is idle: removing directory ${targetDir}" | |
targetDir.deleteRecursive() | |
} else { | |
println " * job is building: not removing directory ${targetDir}" | |
} | |
} | |
return true; | |
} | |
for (node in GetNodes()) { | |
println "Node: '${node.getSelfLabel().toString()}' (" + node.getAssignedLabels().join(", ") + ")" | |
def workspacePathBase = node.getWorkspaceFor(job) | |
println "Workspace: ${workspacePathBase}" | |
// handle concurrent workspaces | |
for (int i=1; i < 1000; i++) { | |
// they are suffixed... | |
workspacePath = i==1 ? workspacePathBase : workspacePathBase.withSuffix(combinator+i); | |
println "Checking ${workspacePath}" | |
if (!CheckWorkspace(workspacePath)) { | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment