python 获取Jenkins上的job的状态
最近在做一个项目的CI双流水线建设,因为一个流水线涉及到多个job,那上一个流水线没有全部结束的话,这边项目要求是不能开始下一个CI流程的,那么,此时就需要判断上一个流程里的所有job是否结束,需要获取job的状态,因此写了下面的代码,仅供参考。
复制或者转发请附上我的链接。
1 import jenkins 2 import time 3 import sys 4 5 6 def login_jenkins(username="账户", password="密码"): 7 server = jenkins.Jenkins("Jenkins服务URL", username=username, password=password) 8 print(server) 9 return server 10 11 12 def get_jobs_status(job_name, server): 13 try: 14 server.assert_job_exists(job_name) 15 except Exception as e: 16 print(e) 17 job_statue = '1' 18 19 # 判断job是否处于排队状态 20 inQueue = server.get_job_info(job_name)['inQueue'] 21 print("任务是否处于排队状态:", inQueue) 22 if str(inQueue) == 'True': # 排队 23 job_statue = 'pending' 24 running_number = server.get_job_info(job_name)['nextBuildNumber'] 25 else: 26 # 没有在排队的job,获取最新一个的执行编号 27 running_number = server.get_job_info(job_name)['nextBuildNumber'] - 1 28 29 try: 30 running_status = server.get_build_info(job_name, running_number)['building'] # 判断job是否在执行中 31 if str(running_status) == 'True': 32 job_statue = 'running' 33 else: 34 # 若running_status不是True说明job执行完成 35 job_statue = server.get_build_info(job_name,running_number)['result'] 36 except Exception as e: 37 # 上面假设job处于running状态的假设不成立,则job的最新number应该是['lastCompletedBuild']['number'] 38 lastCompletedBuild_number = server.get_job_info(job_name)['lastCompletedBuild']['number'] 39 job_statue = server.get_build_info(job_name, lastCompletedBuild_number)['result'] 40 41 return job_statue, running_number 42 43 44 if __name__ == "__main__": 45 server = login_jenkins(username="账户", password="密码") 46 job_name_list = ["job1", "job2", "job3", "job4"..........] # 监控的任务名列表 47 if len(sys.argv) > 1: # 可接受传参,多个请以逗号分隔 48 job_name_list = list(sys.argv[1].split(",")) 49 print(job_name_list) 50 for job_name in job_name_list: 51 num = 0 52 while True: 53 print("\n任务第%d次轮询!"%int(num+1)) 54 job_statue, running_number = get_jobs_status(job_name, server) 55 print("任务执行状态:", job_statue) 56 print("任务执行编号:", running_number) 57 if job_statue in ("pending", "running"): 58 # time.sleep(3*60) # 如果自动化脚本还在执行,新版本的环境部署job需要等待 59 time.sleep(60) 60 num += 1 61 if num == 20: # 控制轮询等待的次数,不能一直等待(看个人场景需求) 62 break 63 else: 64 break