Skip to content

Instantly share code, notes, and snippets.

@rmpestano
Last active July 18, 2019 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmpestano/3103d0d5b218bd52cef0a8af2825252e to your computer and use it in GitHub Desktop.
Save rmpestano/3103d0d5b218bd52cef0a8af2825252e to your computer and use it in GitHub Desktop.
Cleans jenkins job workspace via groovy script

Script below must be executed in jenkinsURL/script by an admin user

Job item = Jenkins.instance.getItemByFullName("JOB_NAME")
          
for (Node node in Jenkins.instance.nodes) {
  // Make sure slave is online
  if (!node.toComputer().online) {
    continue
  } 
  // deletes job workspace for each node (slave)
  FilePath wrksp = node.getWorkspaceFor(item) 
  
  println("Free space " + wrksp.getFreeDiskSpace())
  println("Cleaning ${item.getName()} workspace for node ${node.getNodeName()}...")
  wrksp.deleteContents()
  println("Free space now " + wrksp.getFreeDiskSpace())
} 
@rmpestano
Copy link
Author

rmpestano commented Jul 17, 2019

It can also be invoked via http, ex:

import java.util.Base64;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import java.util.Base64;
...
private final Client jenkinsClient = new ResteasyClientBuilder()
            .connectionPoolSize(10)
            .establishConnectionTimeout(10, TimeUnit.SECONDS)
            .socketTimeout(15, TimeUnit.SECONDS)
            .build();

...
String scriptContent = sb.toString().replace("{JOB_NAME}",job); //scriptContent is the above sample script
WebTarget clientRequest = jenkinsClient.target(JENKINS_URL+"/scriptText");
    	        Form form = new Form();
    	        form.param("script", scriptContent);
    	        Entity<Form> entity = Entity.form(form);
    	        Response response = clientRequest.request(MediaType.APPLICATION_FORM_URLENCODED)
    	                .header("Authorization", "Basic "+Base64.getEncoder().encodeToString(
(System.getProperty("jenkins.admin-user")+":"+System.getProperty("jenkins.admin-pass")).getBytes()))
    	                .post(entity);
    	        if(!Response.Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily())) {
    	            LOG.error("Could not clear job workspace "+job, e);
    	            throw new RuntimeException("Could not clear workspace of job: "+job);
    	        }
...

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