import json import jenkins import requests import os from config import settings # 需要发版的版本号:从jenkins参数中获取 version_branch = os.environ['version'] # 不同项目harbor链接 注意:harbor_url_list必须与pooltest_item_list中的先后顺序一一对应 harbor_url_list = [ 此处保密 ] # 发版xxx环境项目 pooltest_item_list = [ 此处保密 ] # 需要发版的环境 wanted_environment = pooltest_item_list # 链接jenkins username = xxx # jenkins 用户名 password = xxx # jenkins 密码 server = jenkins.Jenkins(r'jenkins地址', username=username,password=password) # 获取最后一次构建镜像版本 def last_successful_image(): last_successful_image = [] for ever in wanted_environment: lastID = server.get_job_info(ever)["lastSuccessfulBuild"]['number']#获取最后一次构建ID # print(lastID) last_build_info = server.get_build_info(ever, lastID)#获取最后一次构建新型(可以从此方法中获取很多想要的东西,包括最新镜像版本其实也可以从这里得到,无需从harbor获取) last_build_image = last_build_info['actions'][0]['parameters'][0]['value']#获取最后一次构建镜像版本 last_successful_image.append(last_build_image) # print(ever+' : '+str(lastID)+' : '+last_build_image) return last_successful_image #返回最后一次构建镜像的列表 # 访问harbor接口获取所有镜像 def image_all(): image_list = [] requests.packages.urllib3.disable_warnings() # 屏蔽错误提醒 s = requests.session() s.auth = ('用户名', '密码') # 链接harbor环境 for ever in harbor_url_list: r = s.get(ever, verify=False) r1 = json.loads(r.text) image_list.append(r1) return image_list # 获取最新镜像 def newest_image(): image_list = [] for image_single_items in image_all(): for row in reversed(image_single_items): # 倒序遍历镜像列表 name = row['name'] if name[2:7] == version_branch: image_list.append(name) break # 匹配到相关版本的镜像后跳出循环 # print(image_list) return image_list # 调取jenkins自动发版 def auto_build(): # 循环遍历不同项目进行发版 for i in range(0, len(wanted_environment)): if newest_image()[i] != last_successful_image()[i]: server.build_job(wanted_environment[i], {'IMAGE_VERS': newest_image()[i]}) #方法build_job print({wanted_environment[i]: newest_image()[i]}) else: continue if __name__ == '__main__': auto_build()
注释:上面标红的为jenkins库的一些方法,详见下述
1. jenkins库安装
sudo pip install python-jenkins
2. 库的使用
import jenkins
#定义远程的jenkins master server的url,以及port
jenkins_server_url='xxxx:xxxx'
#定义用户的User Id 和 API Token,获取方式同上文
user_id='xxxx'
api_token='xxxx'
#实例化jenkins对象,连接远程的jenkins master server
server=jenkins.Jenkins(jenkins_server_url, username=user_id, password=api_token)
不带构建参数:
#构建job名为job_name的job
server.build_job(job_name)
带参数构建:
#String参数化构建job名为job_name的job, 参数param_dict为字典形式,如:param_dict= {"param1":“value1”, “param2”:“value2”}
server.build_job(job_name, parameters=param_dict)
#获取job名为job_name的job的相关信息
server.get_job_info(job_name)
#获取job名为job_name的job的最后次构建号
server.get_job_info(job_name)['lastBuild']['number']
#获取job名为job_name的job的某次构建的执行结果状态
server.get_build_info(job_name,build_number)['result']
#判断job名为job_name的job的某次构建是否还在构建中
server.get_build_info(job_name,build_number)['building']