py调jenkins接口发布并通知 这个需求是我自己给自己安排的,因为每到工作日,基本晚上10点后都要我进行发布(10点后会自动关停系统,直到第二天7点)。天天要我发,老实说,不胜其烦,所以周末在思考,然后写了雏形,今天小改下,就能跑了。 只能说,这个python脚本比较拙劣,刚好满足基本需求,后续需要完善的地方比较多。 脚本思路:
环境准备:python3.6,需要安装jenkins相关模块
pip3 install python-jenkins jenkinsapi
三大组成:获取jenkins操作对象,构建任务并获取结果状态,发钉钉通知
#!/usr/bin/python3.6 #coding=UTF-8 ''' 输入:jenkins服务器的地址,用户名和密码 输出:已构建任务的状态 ''' import datetime, time import jenkinsapi import jenkins import json import sys import requests from jenkinsapi.jenkins import * from jenkinsapi.job import * from jenkinsapi.build import Build ''' 1、获取jenkins操作对象 ''' def jenkins_get_server(): print("start to get") url = "jenkins地址" username='jenkins登录名' password='jenkins登录密码' #实例化jenkins对象,连接远程的 jenkins master server server = jenkins.Jenkins(url, username, password) return server ''' 2、构建任务,获取任务构建状态 ''' def jenkins_get_jobbuildstat(): server = jenkins_get_server() name = '要发布的任务名' param_dict = {'BRANCH': 'main'} server.build_job(name, parameters=param_dict) # 构建任务: 不加参数跑不动--原因未知 # server.build_job('要发布的任务名') # 等4分多钟后,获取任务构建状态--人为观察总结 time.sleep(250) lastbuildNumber=server.get_job_info(name)['lastBuild']['number'] print(lastbuildNumber) job_status = server.get_build_info(name,lastbuildNumber)['result'] print(job_status) # 返回构建任务的状态 if job_status == 'SUCCESS': msg = 'xxx:构建成功' print("最近一次,xxx,构建成功") else: msg = 'xxx:构建失败, 请检查!' print("最近一次,xxx,构建失败!") send_msg(msg) ''' 3、钉钉通知 ''' def send_msg(text): headers = {'Content-Type': 'application/json;charset=utf-8'} api_url = "钉钉机器人url" json_text= { "msgtype": "text", "text": { "content": text }, "at": { "atMobiles": [ "加一的手机号码" ], "isAtAll": False } } result = requests.post(api_url,json.dumps(json_text),headers=headers).content print(result) jenkins_get_jobbuildstat()
运行结果:
最后贴一个获取jenkins任务参数的函数,我觉得蛮有用的,传参构建任务可能会用到
def Url_Get_Job_List(url='jenkins地址', username='jenkins登录用户', password='jenkins登录密码'): server = jenkins.Jenkins(url, username, password) name = "构建任务名" build_arg = server.get_job_info(name)['property'] for parameter_definitions in build_arg: if len(parameter_definitions) > 1: for parameter in parameter_definitions["parameterDefinitions"]: print('----------------------------------') print('name: %s' % parameter["name"]) print('class: %s' % parameter["_class"]) print('type: %s' % parameter["type"]) print('description: %s' % parameter["description"]) print('jenkins_arg: %s' % parameter["defaultParameterValue"]["name"]) print('default_value: %s' % parameter["defaultParameterValue"]["value"]) if parameter["_class"] == 'hudson.model.ChoiceParameterDefinition': print('can_choices: %s' % parameter["choices"]) print('----------------------------------') Url_Get_Job_List()View Code 参考:http://t.zoukankan.com/L-O-N-p-11608220.html 标签:name,py,接口,server,import,print,jenkins,parameter From: https://www.cnblogs.com/windysai/p/16709313.html