龙空技术网

Python 之 Jenkins 分析指定环境发布信息

Candy.W 216

前言:

此刻我们对“python 构建发布模块”可能比较注重,我们都想要了解一些“python 构建发布模块”的相关资讯。那么小编同时在网上汇集了一些关于“python 构建发布模块””的相关文章,希望同学们能喜欢,朋友们快快来学习一下吧!

分享背景

工作中由于部署的工程服务比较多,测试环境也比较多,如果想知道哪个测试环境发布了哪些内容,需要从发布列表中一一肉眼查看,十分费眼。

有没有更便捷的方式来获取这些测试环境的发布内容呢?答案:有的。我们可以通过 Python 结合 Jenkins 包模块来自动分析查看指定环境的发布内容。

代码实现

1.获取 Jenkins 操作对象

# -*- coding: utf-8 -*-import jenkinsjoblists=[]"""   获取jenkins操作对象"""def jenkins_get_server():    print("start to get")    jenkins_server_url = "; #jenkins服务地址    user_id = "tony" #jenkins 登录账号    api_token = "test" #jenkins 登录密码    # 实例化jenkins对象,连接远程的jenkins master server    server = jenkins.Jenkins(jenkins_server_url, username=user_id, password=api_token)    return server

2.获取 Job 信息

"""   获取job的信息"""def jenkins_get_jobs():    # String参数化构建job名为job_name的job, 参数param_dict为字典形式,如:param_dict= {"param1":“value1”, “param2”:“value2”}    # server.build_job(job_name, parameters=param_dict)    server = jenkins_get_server()    for j in server.get_all_jobs():        if("op-beta" in j['fullname']):            # print(j)            joblists.append(j['name'])

3.获取 Job 构建信息

'''    获取job构建的信息'''def jenkins_get_build_number(name):    server = jenkins_get_server()    resp=server.get_jobs(name)    print(resp)

4.获取 Job 最后一次构建信息

"""   获取job的最后一次构建信息"""def jenkins_get_job_info(job_name,env):    server = jenkins_get_server()    lastbuildNumber = server.get_job_info(job_name)['lastBuild']['number']    print(lastbuildNumber)    build_state = get_job_deploy_list_info(server, job_name, lastbuildNumber,env)    print(build_state)

5.从 Job 部署记录中获取 env(测试环境) 发布记录

"""   获取job的部署记录中查找env发布的记录"""def get_job_deploy_list_info(server,name,build_numbers,env):    build_state=name+"-->"+str(build_numbers)+"-->构建完成"    # 获取正在排队构建的job队列 即pending状态中的所有job,如果没有 pending状态的job即返回1个空列表    queue_info = server.get_queue_info()    if queue_info:        for queue_job_info in queue_info:            if queue_job_info['task']['name'] == name:                # msg = 'pending期,排队构建中'                build_state = name+"-->"+str(build_numbers)+'-->pending'    else:        build_state = server.get_build_info(name, build_numbers)['result']  # 构建结束 SUCCESS|FAILURE<class 'str'>  ABORTED <class 'str'> 构建中None None <class 'NoneType'>    # build_env_info=server.get_build_env_vars(name,build_number)    build_type = ""    build_author = ""    build_env_stuat=[]    for i in range(40):        try:            build_info=server.get_build_info(name,build_numbers-i)            # print(build_info)        except:            pass        # 取出编译号        build_number = build_info['number']        # 取出编译时间        build_time = get_time(build_info['timestamp'])        # 取出编译url        build_url = build_info['url']        # 取出编译选择的环境        for dict1 in build_info['actions']:            # print(dict1) #list1 实际上是一个dict1            if("ars-fe-op-beta-cn0"==name):                if ("parameters" in dict1):                    for i in dict1['parameters']:                        if(i['name']=="api_server"):                            build_type=i['value']            if("parameters" in dict1):                for i in dict1['parameters']:                    if(i['name']=="build_profile"):                        build_type=i['value']            #取出服务部署者            if("causes" in dict1 and 'userName' in dict1['causes'][0]):                build_author=dict1['causes'][0]['userName']                    if(build_type==env):            print(str(build_number)+"->"+build_time+"->"+build_type+"->"+build_author+"->"+build_url)    return build_state

6.时间戳转换为str类型的时间格式

"""   #时间戳转换为str类型的时间格式"""def get_time(timestamp):    import datetime    dateArray = datetime.datetime.fromtimestamp(timestamp/1000)    otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")    return otherStyleTime

7.获取所有 Job 在 env 环境上面的部署记录

"""   #获取所有的job在env环境上面部署的记录(近40次)"""def get_all_job_of_evn(env):    jenkins_get_jobs()#需要忽略掉的job名称    ignore_list = ['repeater-test-op-beta-cn0',                   'jacoco-test-op-beta-cn0',                   ]    joblistss = list(set(joblists).difference(set(ignore_list)))    joblistes = []    for apis in joblistss:        if ("api" not in apis):            print(apis)            joblistes.append(apis)    print(joblistes, len(joblistes))    for jobname in joblistes:        jenkins_get_job_info(jobname,env)if __name__=="__main__":    get_all_job_of_evn("stuat")

执行结果

备注: 今天分享的内容是基于 Jenkins 服务端的 Version=2.164

标签: #python 构建发布模块