jenkins 批量添加任务job

最近重构一个Scrapy爬虫项目,需要将300个spider的调度任务在jenkins中添加。这已经超过了手动一个一个添加任务的极限,是时候要借助工具批量添加了。

Jenkins API

Jenkins提供了一套远端访问的API,目前有3种方式:

  • XML

  • JSON with JSONP support

  • Python

远程API可以执行以下这些功能:

  • 创建/复制 job

  • 触发一个新的构建

  • 查询Jenkins的运行状态

Jenkins Job模板

1,创建job

本文的思路是先在网页上手动创建一个Job,然后将Job的配置文件拷贝至本地,制作成模板。

2,配置job

模板job主要有两块内容:

1,【构建触发器】定时构建

  • 【构建】执行shell

其中HOST_TEST,PROJECT_TEST是在jenkins系统配置中设置的环境变量,目的是为了更换scrapyd服务器时更加灵活。

3,制作模板

进入到jenkins的安装目录(默认为/var/lib/jenkins/),在/var/lib/jenkins/jobs/【采集】template目录下找到config.xml文件,拷贝至本地

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.1" encoding="UTF-8"?><project>
<actions/>
<description/>
<keepDependencies>false</keepDependencies>
<properties/>
<scm class="hudson.scm.NullSCM"/>
<canRoam>true</canRoam>
<disabled>false</disabled>
<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
<triggers>
<hudson.triggers.TimerTrigger>
<spec>0 12 * * *</spec>
</hudson.triggers.TimerTrigger>
</triggers>
<concurrentBuild>false</concurrentBuild>
<builders>
<hudson.tasks.Shell>
<command>curl ${HOST_TEST}/schedule.json -d project=${PROJECT_TEST} -d spider='tt_test_spider'</command>
</hudson.tasks.Shell>
</builders>
<publishers/>
<buildWrappers/>
</project>

批量创建的job主要差异在spider名称和crontab定时任务的设置不同,将这两处模板化:

config.xml

该文件中有4个变量要配置:

  • crontab_value

  • spider_name

  • HOST_TEMPLATE

  • PROJECT_TEMPLATE

Python-Jenkins脚本批量创建job

1,安装

1
2

pip install python-jenkins

2,脚本

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
import jenkins
template_xml="config.xml"
#与网页版Jenkins登录的账号、密码一致
server = jenkins.Jenkins('http://yourip:8080/', username='admin', password='admin')

job_list = {
"test1_spider": "30 2 * * *",
"test2_spider": "30 3 * * *",
"test3_spider": "55 11,23 * * *",
}

classify = '采集'
host = 'http://0.0.0.0:6800/'
project = 'test_spider'

for spider_name, crontab in job_list.items():
with open(template_xml) as f:
profile = f.read()

JOB_CONFIG=profile.replace("crontab_value", crontab)\
.replace("spider_name",spider_name)\
.replace("HOST_TEMPLATE", host)\
.replace("PROJECT_TEMPLATE", project)

print(JOB_CONFIG[-200:])

view_name = "【{}】{}_".format(classify, type)
server.create_job(view_name+name, JOB_CONFIG)
# del_job=server.delete_job(view_name+name)
# print(del_job)

3,结果

搞定!分分钟创建了几百个job。

参考

https://wiki.jenkins.io/display/JENKINS/Remote+access+API
批量克隆jenkins的job
https://www.cnblogs.com/znicy/p/5498609.html

Author: Binger Chen
Link: http://www.kekefund.com/2018/08/29/jenkins-jobs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.