任务背景:
Jenkins构建历史记录很多,占用服务器磁盘空间较大,根据开发需求定期删除历史记录。
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 5 import datetime 6 import jenkins 7 import time 8 from jenkinsapi.jenkins import Jenkins 9 10 11 def deleteJobHis(url, username, password): 12 server_jenkins = jenkins.Jenkins(url, username, password) 13 server_Jenkins = Jenkins(url, username, password) 14 15 # 获取所有job列表 16 job_list = server_Jenkins.keys() 17 18 # 获取任务名称及id 19 for job_name in job_list: 20 job_info = server_jenkins.get_job_info(job_name, fetch_all_builds=True)['builds'] 21 # print(job_info) 22 job_id_list = [] 23 for job in job_info: 24 job_id_list.append(job['number']) 25 26 save_days = (datetime.datetime.now() - datetime.timedelta(minutes=43200)).strftime("%Y-%m-%d %H:%M:%S") 27 # print(save_days) 28 save_days = time.strptime(save_days, "%Y-%m-%d %H:%M:%S") 29 30 # 判断构建历史记录,大于5次的保留,其余删除 31 if len(job_id_list) > 10: 32 job_id_list = job_id_list[10:] 33 job_id_list.reverse() 34 35 for job_id in job_id_list: 36 job_time = time.localtime(server_jenkins.get_build_info(job_name, job_id, depth=0)['timestamp'] / 1000) 37 job_time_format = time.strftime("%Y-%m-%d", job_time) 38 print(job_name, job_id, job_time_format) 39 # server_jenkins.delete_build(job_name, job_id) 40 elif len(job_id_list) <= 5: 41 # 判断构建历史记录,小于5次的判断job id的执行时间,超过保留天数的删除 42 for job_id in job_id_list: 43 job_time = time.localtime(server_jenkins.get_build_info(job_name, job_id, depth=0)['timestamp'] / 1000) 44 job_time_format = time.strftime("%Y-%m-%d", job_time) 45 46 if job_time < save_days: 47 print(job_name, job_id, job_time_format) 48 # server_jenkins.delete_build(job_name, job_id) 49 50 51 deleteJobHis( 52 url='', 53 username='', 54 password='', 55 )
标签:Python,time,list,jenkins,job,Scripts,Jenkins,id From: https://www.cnblogs.com/Liangdalong/p/17445651.html