笔者也经常在网上查询信息,但发现很多信息都是照搬,内容甚至有错误,可用性很低.笔者就认为如果要分享就应该把遇到的问题真实的分享出来,让更多同路人少走弯路.节约时间.
觉得这篇文章有帮助的同学可以点个赞!将真有用的信息传递给更多人!
常用的方法
安装 jenkins 依赖
pip install python-jenkins
连接 jenkins
url = 'http://192.168.10.160:8008/jenkins'
username = 'test'
password = 'test'
# 登录jenkins
server = jenkins.Jenkins(url, username=username, password=password)
获取下次构建的编号
job_name = 'py接☐自动化'
server.get_job_info(job_name)['nextBuildNumber']
开始构建
先找到参数(在指定页面的网址后面输入/api/json)
当然你也可以抓包
job_name = 'py接☐自动化'
parameters = {'gitPull':True} # 直接写键值对
build_number = server.build_job(name=job_name, parameters=parameters)
获取构建任务的信息
build_info = server.get_build_info(job_name, build_number)
打印后你将获得巨量的信息
获取当前正在构建的任务编号
build_number = server.get_job_info(build_name)['lastBuild']['number']
获取构建状态
你可以通过轮询来确定对应编号的构建任务是否完成构建
build_status = server.get_build_info(job_name, build_number)['result']
获取构建任务的日志/控制台内容
build_number = 11008
server.get_build_console_output(job_name, build_number )
获取当前任务是否存在排队的构建任务
server.get_queue_info()
设置构建任务的描述/编辑编译信息
自行参考/魔改
def set_build_description(jenkins_server: jenkins.Jenkins, job_name, build_number, data: dict = None,
description=None):
"""
:param jenkins_server: jenkins对象(已登录)
:param job_name: 任务名称
:param build_number: 任务编号
:param data: 参数
:param description: 描述
:return:
"""
# build_number = '282'
# job_name = 'UI-Test'
# url = 'http://192.168.252.122:8080/jenkins/job/jobname/5/configSubmit'
url = f'{jenkins_server.server}job/{job_name}/{build_number}/configSubmit'
my_logger.info(f'设置构建描述为:{description}')
if data is not None:
req_json = data
else:
data_str = {"displayName": "", "description": f"{description}"}
req_json = {'json': f'{data_str}'}
jenkins_server.jenkins_request(requests.Request(url=url, data=req_json, method='POST'))
拼接 jenkins 的构建任务网址
def get_build_number_console_link(next_build_number):
"""
:param next_build_number: 构建编号
:return: 对应构建编号的任务详情界面,例如:http://192.168.252.110:8080/jenkins/job/UI-Test/1492
"""
# 这里你不要无脑复制运行,自己参考示例魔改,每个人的jenkins的网址不同
next_build_number_link = f'http://192.168.252.160:8011/jenkins' \
f'/job/UI-Test' \
f'/{next_build_number}'
return next_build_number_link