1
votes

I was able to kick off a Jenkins pipeline build by sending a post request (with username/password) to Jenkins-Pipeline-URL/buildwithParameter.

Is there a way inside the code to know which build I kicked off and also get the status of that build using some rest API?

1

1 Answers

3
votes

From the Jenkins API documentation:

Accessing Progressive Console Output

You can retrieve in-progress console output by making repeated GET requests with a parameter. You'll basically send GET request to this URL (or this URL if you want HTML that can be put into tag.) The start parameter controls the byte offset of where you start.

The response will contain a chunk of the console output, as well as the X-Text-Size header that represents the bytes offset (of the raw log file). This is the number you want to use as the start parameter for the next call.

If the response also contains the X-More-Data: true header, the server is indicating that the build is in progress, and you need to repeat the request after some delay. The Jenkins UI waits 5 seconds before making the next call. When this header is not present, you know that you've retrieved all the data and the build is complete.

Your url will look something like:

https://Jenkins-Pipeline-URL/lastBuild/logText/progressiveText?start=0

Depending on what you plan to do with the status, you can either keep polling the entire logs, or you can increment the start counter as you read in text based on the number of characters read. This will give you new running output from the build.

Also from the documentation:

https://Jenkins-Pipeline-URL/lastBuild/buildNumber

This URL returns the build number in text/plain format.

If you only wish to obtain whether the build passed or failed:

https://Jenkins-Pipeline-URL/lastBuild/api/json

Will return json (or xml if json is replaced in the url) that can be parsed for the result object:

"result":"SUCCESS"

You can create repeated GET requests, similar to the first answer, to get an updated status.