I need to get the ID of a jenkins job that I start using the REST API (using python). Since Jenkins 1.529, it seems to be possible to trigger a build using the API abd to get in return an url pointing to the job in the queue.
Documentation of Jenkins:
Perform a build
To programmatically schedule a new build, post to this URL. If the build has parameters, post to this URL and provide the parameters as form data. 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.)
But I do not succeed in getting an useful url.
I tried:
import requests
requestKwargs ={'headers': {'Content-Type': 'application/x-www-form-urlencoded'}, 'data': {'json': '{"parameter": []}'}, 'verify': True}
url=server+'job/test/build/'
req=requests.post(url, **requestKwargs)
print 'status',req.status_code
location=req.headers['location']
print 'location is:',location
The output of this code is:
status 201
location is: http://SERVER_PORT/job/test/build/
How can I use the information of "location" to track the status of the queue task?
Thanks.
I've worked around this issue by providing an 'ident' param to jobs that I wish to interact with programatically.
When submitting the job, I generate a uuid and submit this as the ident param to /job/<job_name>/buildWithParameters
.
I then get /queue/api/json
and iterate through the list of queued items, searching for an item with that uuid in it's params. That gets the queue id.
I then use this queue id to poll /queue/item/<queue_id>/api/json
every N seconds, waiting for jenkins to provide a build number in the response (it will once the build has started). You can use this build number to construct the url you want, /job/<job_name>/<build_number>
.
You actually need to add the ident as a param in your jenkins job. It's a pain, but it works reliably.
You need to add a header to your request:
Accept: application/json
And then it should work. Believe it or not, I had to read the source to figure this out... you can read the relevant snippet here.
EDIT: Apparently, though this does return the information for the project, it doesn't return the job that has just been queued! It's a known issue. The bug is #13546.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With