最近在将小程序自动化整合到平台,主要借助的是jenkins;本文主要讲解一下jenkins常用的api
1 获取jenkins链接
import jenkins
base_config = {
'url': 'jenkins_url',
'username': 'admin',
'password': '123456'
}
jenkins_server = jenkins.Jenkins(**self.base_config)
2 创建job
# 这里config_xml 是要创建jenkins的配置文件
# 可以在jenkins对应的job路径后拼接config.xml获取配置模板
# 如http://xxxx/job/xxx/config.xml
jenkins_server.create_job(job_name, config_xml)
3 删除job
# 直接传入名称即可
jenkins_server.delete_job(job_name)
4 修改job
# 这里同样需要传配置文件
jenkins_server.reconfig_job(job_name, config_xml)
5 构建job
jenkins_server.build_job(job_name)
6 获取job信息
# 获取job信息
job_info = jenkins_server.get_job_info(job_name)
# 获取job最后一次构建信息编号
res = job_info ['lastCompletedBuild']['number']
# 查看job是否处于队列当中
isInQUeue = job_info ['inQueue']
# 获取正在构建的编号
building_num= job_info ['nextBuildNumber']-1
7 获取构建信息
# build_num为构建编号
build_info = jenkins_server.get_build_info(job_name, build_num)
# 查看是否正在构建
isBuilding = build_info['building']
# 获取构建结果
res = build_info ['result']
8 获取控制台输出日志
# number为构建编号
log = jenkins_server.get_build_console_output(name=job_name, number=build_num)
等待运行结束后获取结果
def is_job_in_queue(self, job_name: str) -> bool:
"""
获取job是否处于队列状态
:return: 是否处于队列
"""
return self.get_job_info(job_name)['inQueue']
def is_job_building(self, job_name) -> bool:
"""
获取job是否处于构建当中
:param job_name: job名称
:param number: 构建编号
"""
building_num = self.get_building_num(job_name)
if building_num == 0: return False
return self.get_build_info(job_name, building_num)['building']
def get_building_num(self, job_name: str) -> int:
"""
获取job当前正在运行的number
"""
return self.get_job_info(job_name)['nextBuildNumber'] - 1
def get_last_build_result(self, job_name) -> str:
"""
获取最后一次构建信息
:param job_name: job名称
:return:
"""
last_build_num = self.get_last_build_num(job_name)
return self.jenkins_server.get_build_info(job_name, last_build_num)['result'] if last_build_num != -1 else ''
def wait_finish_get_result(self, job_name):
is_in_queue = True
while is_in_queue:
is_in_queue = self.is_job_in_queue(job_name)
if not is_in_queue: break
time.sleep(3)
# 获取最新的构建num
running_number = self.get_building_num(job_name)
is_building = True
while is_building:
# 需要先判断是否在队列中
is_building = self.is_job_building(job_name)
if not is_building: break
time.sleep(2)
# 获取最后一次构建的结果
return self.get_last_build_result(job_name)