Issue
Using the REST API, how do I trigger a new build for a job, and get the build number for that new build?
Environment
- CloudBees CI (CloudBees Core)
- CloudBees CI (CloudBees Core) on modern cloud platforms - Managed Master
- CloudBees CI (CloudBees Core) on modern cloud platforms - Operations Center
- CloudBees CI (CloudBees Core) on traditional platforms - Client Master
- CloudBees CI (CloudBees Core) on traditional platforms - Operations Center
- CloudBees Jenkins Enterprise
- CloudBees Jenkins Enterprise - Managed Master
- CloudBees Jenkins Enterprise - Operations Center
- CloudBees Jenkins Platform - Client Master
- CloudBees Jenkins Platform - Operations Center
- CloudBees Jenkins Distribution
- Jenkins LTS
Resolution
1. Modify JENKINS_URL, USER, and API_TOKEN in the following script to match your specific environment to start a non-parameterized build from a shell script:
#!/bin/bash
BUILD=$1
JENKINS_URL=http://jenkins.example.com
USER=admin
API_TOKEN=11605789ab3612a2193b982b07ed32468b
JENKINS_CRUMB=$(curl -q -u ${USER}:${API_TOKEN} "${JENKINS_URL}/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)")
curl -u ${USER}:${API_TOKEN} -H "${JENKINS_CRUMB}" -i -X POST ${JENKINS_URL}/job/${BUILD}/build
This will yield the following output:
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 46 100 46 0 0 5270 0 --:--:-- --:--:-- --:--:-- 5750
HTTP/1.1 201 Created
Date: Wed, 15 May 2019 15:52:26 GMT
X-Content-Type-Options: nosniff
Location: http://jenkins.example.com/queue/item/5/
Content-Length: 0
Server: Jetty(9.4.z-SNAPSHOT)
NOTE: The queue URL (in this example http://jenkins.example.com:8080/queue/item/5/) will expire 5 minutes after the queue item is assigned a build number for the job so the URL will stay valid even if the build sits in the build queue for a long time.
2. Use curl to query api/ of the Location URL from Step 1 to get the build number
curl -u ${USER}:${API_TOKEN} -H "${JENKINS_CRUMB}" 'http://jenkins.example.com/queue/item/5/api/json?pretty=true'
This will yield the following output:
{
...
"executable" : {
"_class" : "hudson.model.FreeStyleBuild",
"number" : 5
"url" : "http://jenkins.example.com:8080/job/test/5/"
}
3. The URL (in this example http://jenkins.example.com:8080/job/test/5/) will be there once the queue item gets assigned a build number.
0 Comments