Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get previous build result

I want to emulate the original Jenkins behaviour of doing stuff (like sending out notifications) when builds become unstable / fail or become successful again.

For that I need to query the previous build status, which can be done like this:

currentBuild.rawBuild.getPreviousBuild()?.getResult().toString()

However, rawBuild is supposed to be a "dangerous" object and as thus blacklisted and cannot be executed inside the Groovy sandbox.

Now, since I'm loading my Jenkins scripts from SCM, there is no way for me to deactivate the Groovy sandbox on a per-project level, but only for the whole Jenkins instance (i.e. through this), and this is certainly not something I want.

Is there any other way of determining the last build status of a job that conforms with the sandbox principles (and does not include hacks like querying the status via Jenkins' REST API) that I have missed?

like image 760
Thomas Keller Avatar asked Oct 27 '16 12:10

Thomas Keller


People also ask

What is currentBuild in Jenkins?

currentBuild is a global variable that may be used to refer to the currently running build.

How do I get Jenkins build status?

Yeah, Jenkins has an API which gives building status, Last Job build status(failed or Success) and some other useful information in JSON format. This is the API /job/your_job_name_here/lastBuild/api/json .

How do I remove old builds in Jenkins?

Delete a Jenkins build via GUI. Go into the build you want to delete, and click the Delete this build button in the upper right corner. If you need to clean the Jenkins build history, and reset the build number back to 1, you can run a simple script in Jenkins Script Console.


1 Answers

No need to access rawBuild, instead you can do the following without any special permissions:

currentBuild.getPreviousBuild().result

This will allow you to see the result of the previous build without needing to have any special privileges set by the Jenkins administrator. It should be able to be run anywhere.

Global Variable Reference: https://www.jenkins.io/doc/book/pipeline/getting-started/#global-variable-reference

And more specifically, in your own Jenkins: ${YOUR_JENKINS_URL}/pipeline-syntax/globals#currentBuild

More information: https://support.cloudbees.com/hc/en-us/articles/217591038-How-to-Iterate-Through-the-Last-Successful-Builds-in-Pipeline-Job

like image 136
Nick Avatar answered Oct 16 '22 16:10

Nick