随着微服务项目越来越多,每一次上线发布很多个构建job要手动构建很费时费力,所以能自动咱就不手动。
脚本环境基于python3,需要安装的模块是python-jenkins这个api库来说实现!关于api库使用请参考官方文档:API reference — Python Jenkins 1.1.1.dev1 documentation
脚本是通过遍历文本里的构建job名称和构建参数来实现批量构建,把构建完成的信息结果是保存输出到output.log文件里。
如果是多分支流水线job,job_name改为: "name/branch".例如:job为:test,分支为:dev,job_name="test/dev"
import os
import time
import jenkins
def loglin_jenkins():
jenkins_url = 'url'
jenkins_user = 'user'
jenkins_password = 'passwd'
server = jenkins.Jenkins(jenkins_url, jenkins_user, jenkins_password)
return server
def build_jobs(job_path):
with open(job_path, 'r', encoding='utf-8') as f:
# 遍历文本取出job名和构建参数值
for i in f.readlines():
line = i.strip().split()
# 去掉文本上下的空行
if not line:
continue
# job名和构建参数值
job_name, image_tag = line
# 构建需的参数,字典形式可以有多个参数
parameters = {'image_tag': image_tag, 'jira_num': 'SOP-0000'}
# 当前构建次数编号
start_lastbuildNumber = server.get_job_info(job_name)['lastBuild']['number']
# 当前构建的状态
start_status = server.get_build_info(job_name, start_lastbuildNumber)['building']
# 判断当前否在构建当中
if not start_status:
print('-' * 10 + '开始构建任务.job名为:%s.' % job_name)
server.build_job(job_name, parameters)
else:
print('当前构建任务[%s]已在构建当中...' % job_name)
def get_log(log_path, job_path):
# 清空初始log文件内容
if os.path.exists(log_path):
with open(log_path, 'r+') as file:
file.truncate(0)
with open(job_path, 'r', encoding='utf-8') as f:
# 遍历文本取出job名
for i in f.readlines():
line = i.strip().split()
# 文件假如上下有空行就去掉上下的空行
if not line:
continue
job_name = line[0]
# 检查job的构建状态是否完成,把结果输出到output.log日志里
while True:
end_lastbuildNumber = server.get_job_info(job_name)['lastBuild']['number']
end_status = server.get_build_info(job_name, end_lastbuildNumber)['building']
if end_status:
print('%s正在构建.......' % job_name)
else:
build_info = server.get_build_info(job_name, end_lastbuildNumber)
result = build_info['result']
start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(build_info['timestamp'] / 1000))
print('Job名:%s,最后一次构建号:#%d,构建开始时间:%s,构建状态:%s.' % (job_name, end_lastbuildNumber, start_time, result))
with open(log_path, 'a+', encoding='utf-8') as f1:
f1.write('Job名:%s,最后一次构建号:#%d,构建开始时间:%s,构建状态:%s\n' % (job_name, end_lastbuildNumber, start_time, result))
break
if __name__ == '__main__':
server = loglin_jenkins()
log_path = 'E:\study\output.log'
jobname_path = 'E:\study\jobname.txt'
build_jobs(jobname_path)
time.sleep(10)
get_log(log_path, jobname_path)