Python-Jenkins官网:https://pypi.python.org/pypi/python-jenkins/
Python-Jenkins Doc:http://python-jenkins.readthedocs.io/en/latest/index.html
最近在工作中需要用到在后台代码中触发Jenkins任务的构建,于是想到Jenkins是否有一些已经封装好的API类库提供,用于处理跟Jenkins相关的操作。在Jenkins官网上找到了Python-Jenkins API,仔细阅读后发现,它几乎涵盖了大部分Jenkins的操作,大大方便了我们在后台进行对Jenkins的一些列操作。但是在构建任务的时候碰到了无法传递部分参数的情况,具体问题如下:
参数类型为Filesystem object type的script参数无法传输导致构建失败:
发现构建失败,缺少script参数
代码如下:
# -*- coding:utf-8 -*- import jenkins # 定义远程的jenkins master serve的url,port,username,password jenkins_server_url = "http://172.17.43.16:8080" username = "yuanxihui" password = 'Pcfvumjn"y`zw*#/;fEy' # 实例化jenkins对象,连接远程的jenkins master serve server = jenkins.Jenkins(jenkins_server_url, username=username, password=password) param_dict = { "script": "client-interface.jmx", "threads": "1", "loop": "1", "rampup": "1", "username": "**", "password": "**", "host": "**.**.**.**", "port": "8989" } url = server.build_job("performance-testing-jmeter", parameters=param_dict)
运行构建后缺少script参数。
然后,直接使用requests库查看前端发送的接口,直接通过接口访问,参数传递成功
import requests # 登录jenkins的用户名和密码 username = "****" password = '****' session = requests.Session() login_data = { "j_username": username, "j_password": password , "from": "/", "Submit": "登录" } login_resp = session.post(url="http://ip:8080/j_acegi_security_check", data=login_data) print(login_resp.status_code) crumb_resp = session.get(url="http://ip:8080/crumbIssuer/api/json") crumb_resp_dict = crumb_resp.json() crumb = crumb_resp_dict['crumb'] print(crumb) build_data = { "script": "client-interface.jmx", "threads": "1", "loop": "1", "rampup": "1", "username": "***", "password": "**", "host": "ip.35", "port": "8989", "statusCode": "303", "redirectTo": ".", "Jenkins-Crumb": crumb, "json": '{"parameter": [{"name": "script", "value": "client-interface.jmx"}, {"name": "threads", "value": "1"}, {"name": "loop", "value": "1"}, {"name": "rampup", "value": "1"}, {"name": "username", "value": "***"}, {"name": "password", "value": "***"}, {"name": "host", "value": "**.**.**.**"}, {"name": "port", "value": "8989"}], "statusCode": "303", "redirectTo": ".", "Jenkins-Crumb": '+crumb+'}', "Submit": "开始构建" } build_resp = session.post(url="http://ip:8080/job/performance-testing-jmeter/build", data=build_data) print(build_resp.status_code) session.close()