【背景】:部门在搞持续集成,使用jenkins作为核心调度,要再其基础上进行二次封装,所以需要研究下jenkins的api。笔者主要负责搭建平台,在研究用法也花费了些时间,本文主要做个简要的记录,希望能为各位朋友节省时间。
【环境】:(默认读者已经具备了基本的持续集成经验和jenkins用法)
1. Jenkins1.455
2. 系统Suse
3. Tomcat 6.0.37
4. Java 1.6.0_26
【API介绍】
Jenkins提供了html、json、python API,实质都是以http get/post方式调用的。查看http://www.xxx.xxx/jenkins/api/ 即可得到相应的说明,如图:
【API实践】
1.创建
curl -X POST http://www.xxx.xxx/jenkins/createItem?name=JavaStd --user peterguo:peterguo --data-binary "@javastd.config.xml" -H "Content-Type: text/xml"
2.禁用
curl -X POST http://www.xxx.xxx/jenkins/job/JavaStd/disable --user peterguo:peterguo
3.启用
curl -X POST http://www.xxx.xxx/jenkins/job/JavaStd/enable --user peterguo:peterguo
4.删除
curl -X POST http://www.xxx.xxx/jenkins/job/JavaStd/doDelete --user peterguo:peterguo
5.获取项目描述
curl -X GET http://www.xxx.xxx/jenkins/job/JavaStd/description --user peterguo:peterguo
6.获取配置文件
curl -X GET http://www.xxx.xxx/jenkins/job/JavaStd/config.xml --user peterguo:peterguo
7.触发SCM检查
curl -X GET http://www.xxx.xxx/jenkins/job/JavaStd/polling --user peterguo:peterguo
8.普通触发
curl -X GET http://www.xxx.xxx/jenkins/job/JavaStd/build --user peterguo:peterguo
9.带参数触发
curl -X GET "http://www.xxx.xxx/jenkins/job/helloworld-freestyle/buildWithParameters?bAllTest=&Choices=2&strParam=abc" --user peterguo:peterguo
10.带参数和补丁触发
curl -X POST "http://www.xxx.xxx/jenkins/job/helloworld-freestyle/buildWithParameters?bAllTest=&Choices=2&strParam=abc" --user peterguo:peterguo -F "action=upload" -F "[email protected]"
注:带补丁触发需要先安装补丁插件,并设置项目的补丁参数
【Python调用】
提供python使用pycurl调用的例子片段,实际和curl调用一样,优点是易整合。
import pycurl url = "http://10.129.145.112:8081/jenkins/job/helloworld-freestyle/config.xml" crl = pycurl.Curl() crl.setopt(pycurl.VERBOSE,1) crl.setopt(pycurl.FOLLOWLOCATION, 1) crl.setopt(pycurl.MAXREDIRS, 5) crl.setopt(pycurl.USERPWD, "peterguo:peterguo") crl.setopt(pycurl.CONNECTTIMEOUT, 60) crl.setopt(pycurl.TIMEOUT, 300) crl.setopt(pycurl.HTTPPROXYTUNNEL,1) crl.fp = StringIO.StringIO() crl.setopt(pycurl.URL, url) crl.setopt(crl.WRITEFUNCTION, crl.fp.write) crl.perform() ret = crl.fp.getvalue()