通过 URL 来触发 Jenkins 任务,进一步可以携带参数完成指定工作
Jenkins Configure
关闭选项 Manage Jenkins
-> Configure Global Security
-> Prevent Cross Site Request Forgery exploits
这样可以使用
curl --user 'USER:PASSWD' -X POST "http://your-jenkins.com/job/Two/build?token=A-Token"
curl --user 'USER:USER-API-Token' -X POST http://your-jenkins.com/job/Two/build?token=A-Token
如果不关闭上述选项,则需要先获得一个 CSRF protection token
,然后再将这个 token
作为 HTTP 请求的 header
发送过去
$ curl --user 'USER:API-Token' http://your-jenkins.com/crumbIssuer/api/json
{"_class":"hudson.security.csrf.DefaultCrumbIssuer","crumb":"xxxxxxxxxxxxxxxxxxx","crumbRequestField":"Jenkins-Crumb"}
$ curl --user 'USER:API-Token' -H "Jenkins-Crumb:xxxxxxxxxxxxxxxxxxx" -X POST http://your-jenkins.com/job/Two/build?token=A-Token
脚本
#!/bin/bash
CRUMB=$(curl -s 'http://guowei:38e2427ac39d5a5f810c83c6fd39ee80 @your-jenkins.com/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)')
curl -u guowei:38e2427ac39d5a5f810c83c6fd39ee80 -H "$CRUMB" -X POST "http://your-jenkins.com/job/Two/build" --data token=A-Token --data delay=0sec
不带参数触发 Job
New Item
-> Build Trigger
-> Trigger builds remotely (e.g., from scripts)
其中 Authentication Token
中填写的字符串即 A-Token
执行上述脚本即触发指定 Job
构建
带参数触发 Job
New Item
-> General
-> This project is parameterized
-> String Parameter
中选择 Name
用于传输参数,例如选择 os
,在 shell
中可以使用 ${os}
进行引用
New Item
-> Build Trigger
-> Trigger builds remotely (e.g., from scripts)
其中 Authentication Token
中填写的字符串即 A-Token
curl -X POST http://<jenkins URL>/jenkins/job/TESTS/job/<Your job's Name>/buildWithParameters \
--user <Jenkins account>:<account's TokenID> \
--data token=<job's token (if required)> \
--data MessageText=Le%20Texte