jenkins 远程调用如何获取构建编号

3,898 阅读2分钟

背景

随着devops概念的越来越为大众所接受, 大家对jenkins的使用越来越频繁, 随之而来的就是在各种系统中接入jienkins, jenkins 也提供了对应的远程调用的api, 但是,jenkins构建api的response里并没有直接返回任务的构建编号, jenkins api的官方文档并没有明确地指出怎么获取该次构建的构建编号, 只是说轮询 location里面的链接可以获得队列任务的状态, 不认真看文档的同学很容易就忽略了:

Either way, the successful queueing will result in 201 status code with Location HTTP header pointing the URL of the item in the queue. By polling the api/xml sub-URL of the queue item, you can track the status of the queued task. Generally, the task will go through some state transitions, then eventually it becomes either cancelled (look for the "cancelled" boolean property), or gets executed (look for the "executable" property that typically points to the AbstractBuild object.)

获取队列编号

通过

http://localhost:8080/job/jobName/build 或者 http://localhost:8080/job/jobName/buildWithParameters?bbbbb=bbbbbb&ccc=ccc api触发jenkins后返回的response 如下图

当status 是201时, 代表执行成功, 在response的headers里面可以找到location字段,其值是一个url, 如 http://localhost:8080/queue/item/10702, 其中10702代表该次构建的队列编号, 在任务执行后, 这个值会对应一个构建编号。

获取构建编号

获取构建编号可以通过两种方式: 通过location链接查询和通过builds tree查询

通过location链接查询构建编号

拿到location后, 查询 http://localhost:8080/queue/item/10702/api/xml

  • 当任务处于队列中时, 返回一个blockedItem的xml

  • 当任务不再处于队列中时,返回一个 leftItem 的xml, 此时任务的构建编号就在其中。

注意:当任务不再处于队列中时, location链接的api查询的有效期只有大概5分钟, 过期以后就会返回404

通过builds tree查询构建编号

通过api http://localhost:8080/job/你的任务名称/api/xml?tree=builds[queueId,number,result]&xpath=//build[queueId=你的队列编号] 也可以查询到对应的构建编号和构建结果,详情如下图所示

任务处于队列中。 任务处于队列中时是查询不到结果的

任务未构建完成。 由于未构建完成, 所以查询不到构建结果

任务已构建完成

总结

综上所述, 只要保存好启动jenkins任务时返回的队列编号,无论是通过location对应的链接还是builds tree的方式都能查询到对应的构建编号, 唯一需要注意的是: location 链接是有有效期的, 超时以后就无法使用了。