Background
I am working on a project that depends using Jenkins with vast number of jobs dynamically created.
We had a use-case where the Jenkins job[s] needs to be deleted. Based on analysis of the REST API offered by Jenkins, I was not able to find the API to delete multiple jobs.
We can delete every job through the API, however that would be very chatty, had the user opted to delete more than 2 or 3 jobs at a time. In order to improve the performance, I decided to build a Jenkins job that does the job of deleting multiple jobs
Job Selection in Jenkins
In Jenkins, we might be having jobs at the root level or contained within folders and in case of having then under folders, we might be having the multiple folders nested.
Jenkins has a name for a job which is just name of the job and a fullName that is the full jenkins path inclusive of the folders that contain this job from the jenkins root.
In order to select a suitable collection of jobs, we must prefer to use the fullName based name validation so as not to delete all matching jobs outside our intended folders hierarchy.
The following groovy script filters for the matching jobs by the given names and then returns the matched jobs so that, they can be processed further.
import jenkins.model.Jenkins;
import hudson.model.AbstractProject
def jobNames = build.buildVariableResolver.resolve("jobsToDelete").split(',')
println(jobNames);
def matchedJobs = Jenkins.instance.getAllItems(AbstractProject.class).findAll {it ->
jobNames.contains(it.fullName);
}
Now that we have the matched jobs, we could delete or disable them as like below.
matchedJobs.each{j -> println("deleting job: "+j.fullName); j.delete(); }
This simple script can be used either in the jenkins build step using groovy or also used in the script execution page in jenkins available in the url: http://jenkins-url/script
Comments
Post a Comment