Saturday, April 20, 2019

Jenkins Delete Jobs under (nested) views

'''
Script to delete jobs and nested views in Jenkins CI including the parent view.
This currently works when you have two-level nested views with jobs under the child view.
Parent view
- Child view 1
- Job 1
- Job 2
- Child view 2
- Job 3
- Job 4
The script will first delete all the jobs in child view, then proceed to delete the child view itself.
Once all child views have been deleted, it will delete the parent view as last step.
License: MIT
'''
import sys
import requests
# Update Jenkins end-point here upto the context path for view with trailing slash
jenkins_endpoint_url="http://localhost:8005/view/"
#######################################
#### DONT MODIFY BELOW
# First arg is username
user = sys.argv[1]
# Second arg is password
passw = sys.argv[2]
# Third arg is the view name
view_to_delete = sys.argv[3]
'''
Method to invoke REST-API call to delete jobs
'''
def delete_job(job):
del_job_req = requests.delete(job['url'], auth=(user, passw))
if(del_job_req.status_code == 200):
print ">>>> Job " + job['name'] + " deleted successfully."
else:
print ">>>> Exception occurred deleting job. HTTP status code: " + str(del_job_req.status_code)
sys.exit();
'''
Method to invoke REST-API call to delete views
'''
def delete_view(view):
request = requests.post(view['url'] + 'doDelete' , auth=(user, passw))
if(request.status_code == 200):
print ">>>> View " + view['name'] + " deleted successfully."
else:
print ">>>> Exception occurred deleting view. HTTP status code: " + str(del_view_req.status_code)
sys.exit()
#### Start of script
# Fetch list of all nested views
nested_view_list_req = requests.get(jenkins_endpoint_url + view_to_delete + '/api/json', auth=(user, passw))
if(nested_view_list_req.status_code == 200):
for app_view in nested_view_list_req.json()['views']: # Loop through each nested view
print "Processing: " + app_view['name']
# Get each job under the nested views
nested_view_req = requests.get(app_view['url'] + 'api/json', auth=(user, passw))
if(nested_view_req.status_code == 200):
# Loop through each jobs in the nested view and delete them
for jobs in nested_view_req.json()['jobs']:
delete_job(jobs)
print "Deleting nested view " + app_view['name'] + " now"
# Delete each of the nested view
delete_view(app_view)
else:
print "Unable to get list of jobs in the view. Error code: " + str(nested_view_list_req.status_code)
if(nested_view_list_req.status_code == 200):
print "Lastly deleting parent view: " + view_to_delete
delete_view(nested_view_list_req.json())
print "All done"
view raw delete-jobs.py hosted with ❤ by GitHub

No comments:

Post a Comment