Java – Jenkins – groovy script – get last successful build date in dd-mm-yyyy format

dategroovyjavaJenkins

I'm using "groovy script" plugin as part of my Jenkins build. I wish to find the last successful build date of a job "RegularBuild" however all the examples online e.g.

import hudson.model.Build;
def buildA = build("jobA")
println(buildA.getProject().getLastSuccessfulBuild())

don't compile even though this seems to be ok.

Not sure how people are using this scripting language but the fundamentals fail. To add to the pain I'm unable to get a valid error comment, all I get is the same error whatever I enter, i.e. the plugin is not helpful at all.

If anyone could help with the correct syntax or even solve the whole problem and provide the date of the last successful build that would be great. One last thing, no xml solutions please as there is nothing in Jenkins that can assign this value to an ENVIRONMENT VARIABLE, well that I know of. Thanks

Best Answer

Following sample will help you. I generally find it useful to setup a plugin development environment and see the actual Types and check documentation

import jenkins.model.Jenkins

def item = Jenkins.instance.getItem("your-job-name")
def  f=item.getLastFailedBuild()

println f.getTime()



def  ff=item.getLastSuccessfulBuild()
println ff.getTime().format("YYYY-MMM-dd HH:mm:ss")
println ff.getTime().format("dd-MM-yyyy")

Edit

(From comments of @Steven the Easily Amused ) If the Jenkins uses folders , then you need getItemByFullName("/folder/yourjobname")

Edit 2

Fix date/time format s/MM:SS/mm:ss/ (substitute digits-of-month:milliseconds with minutes:seconds)

Related Topic