Python Jenkins-Jenkins库初识(调用Job执行)

Jenkins库初识(调用Job执行)

from threading import Event, Thread
import jenkins
import threading
import logging
import datetime

FORMAT = '%(asctime)s %(threadName)s %(thread)s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)

# server = jenkins.Jenkins('http://jenkins.pingcode.live', username='daizhe', password='EgKXD1LY01mxhufr')
server = jenkins.Jenkins('http://localhost:8080/', username='root', password='12345678')
all_jobs = server.get_all_jobs()
# print(all_jobs)

# 事件驱动器
event = Event()   # False

def jobstart(e, name):
    worker_jobs = []
    for item in all_jobs:
        # Job名称
        names = item['name']
        # Job链接
        urls = item['url']
        # Job状态颜色
        colors = item['color']
        # print(item['name'], item['url'], item['color'])
        if names == name:
            logging.info("{}. 开始部署!!!!")
            server.build_job(name)
            lastbuildNumber = server.get_job_info(name)['lastBuild']['number']
            worker_jobs.append(lastbuildNumber)
        e.set()             # True

def jobwatch(e, name):
        e.wait()
        try:
            # 获取job名为testJob的job的最后次构建号
            lastbuildNumber = int(server.get_job_info(name)['lastBuild']['number']) + 1
            logging.info("Job Number : {}".format(lastbuildNumber))

            # 获取job名为testJob的job的最后1次构建的执行结果状态
            # print(server.get_build_console_output(name, number=lastbuildNumber))

            # 判断Job是否还在构建中
            status = server.get_build_info(name, lastbuildNumber)['building']  # bool
            print(status, '`````````')

            while True:
                if status:
                    logging.info("{}. 已经部署完毕!!!".format(name))
                else:
                    logging.info("{}. 正在部署中!!!".format(name))
                    # while True:
                    #     if
                    break
        except Exception as e:
            print(e)
        finally:
            pass

if __name__ == "__main__":
    job_name = "itsm_pipeline_test_job"
    th1 = threading.Thread(target=jobstart, name='jobstart', args=(event, job_name))
    th2 = threading.Thread(target=jobwatch, name='jobwatch', args=(event, job_name))
    th1.start()
    th2.start()



# print("所有的Job信息打印")
# for jb in all_jobs:
#     names = jb['name']
#     print(names, sep='')



# Job_name = input("输入Job名称 >>>")



# 参数
# param_dict = {"RUN_EVN" : "RUN_EVN",
#               "TAG_NAME" : "TAG_NAME",
#               }




        # console = server.get_build_console_output(names)
        # print(console)


    # 问题 :
        # 如何检索出视图,然后再遍历视图中的job



    # build_info = server.get_job_info(item['name'])
    # print(build_info)
posted @ 2021-05-30 14:14  SRE运维充电站  阅读(322)  评论(0编辑  收藏  举报