Jenkins具有丰富的API接口,可以通过调用API接口实现对Job的触发、删除、查看任务状态等操作,支持HTTP协议,支持用户名、密码认证,提供的这些接口可以实现对 Jenkins 的控制。下面介绍Jenkins API的使用实例。
先创建一个有Job任务运行和状态查询权限的用户,可使用admin用户;新建一个项目(可参考持续集成平台Jenkins介绍)
Jenkins API调用示例
远程调用 Jenkins API返回最新任务编号
GET请求
URL:http://username:password@hostname:port/job/任务名/lastBuild/buildNumber
1 | import requests |
输出:1
17
远程调用 Jenkins API查询任务状态
GET请求
URL:http://username:password@hostname:port/job/任务名/\
1 | import json |
返回的日志1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42{
"_class": "hudson.model.FreeStyleBuild",
"actions": [
{
"_class": "hudson.model.CauseAction",
"causes": [
{
"_class": "hudson.model.Cause$UserIdCause",
"shortDescription": "Started by user anonymous",
"userId": null,
"userName": "anonymous"
}
]
},
{},
{
"_class": "org.jenkinsci.plugins.displayurlapi.actions.RunDisplayAction"
}
],
"artifacts": [],
"building": false,
"description": null,
"displayName": "#17",
"duration": 109,
"estimatedDuration": 222,
"executor": null,
"fullDisplayName": "demo #17",
"id": "17",
"keepLog": false,
"number": 17,
"queueId": 3,
"result": "SUCCESS",
"timestamp": 1615705287802,
"url": "http://192.168.30.8:8080/job/demo/17/",
"builtOn": "",
"changeSet": {
"_class": "hudson.scm.EmptyChangeLogSet",
"items": [],
"kind": null
},
"culprits": []
}
远程调用 Jenkins API启动任务
使用POST请求方法:
URL:http://username:password@hostname:port/job/任务名/build
1 | import requests |
Jenkins 跨站请求伪造保护采取 Crumb(碎片生成器),可以使用用户的API Token来进行认证:
1 | import requests |
API Token可以在用户配置中生成。
Python jenkinsapi库
jenkinsapi库封装了Jenkins api 的调用方法
安装:
1 | $ pip install jenkinsapi |
下面代码实现启动job名为demo的任务1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24from jenkinsapi.jenkins import Jenkins
jk = Jenkins('http://192.168.30.8:8080', username='admin', password='admin', useCrumb=True)
# print(jk.keys())
job_name = 'demo'
if jk.has_job(job_name):
my_job = jk.get_job(job_name)
if not my_job.is_queued_or_running():
try:
last_build = my_job.get_last_buildnumber()
except:
last_build = 0
build_num = last_build + 1
# 启动任务
try:
jk.build_job(job_name)
except Exception as e:
print(str(e))
while True:
if not my_job.is_queued_or_running():
print("Finished")
print(f"build_num:{build_num}")
break
输出:1
2Finished
build_num:20
本文标题:持续集成:Jenkins API简单使用
文章作者:hiyo
文章链接:https://hiyongz.github.io/posts/continuous-integration-for-jenkins-api/
许可协议:本博客文章除特别声明外,均采用CC BY-NC-ND 4.0 许可协议。转载请保留原文链接及作者。