Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 354
fabtrg Avatar asked Aug 24 '15 11:08

fabtrg


People also ask

How do I get the latest build number from another job in Jenkins pipeline?

Consider using getItemByFullName() instead of getItem() . This can be important if you have folders and the jobName is in another folder.

How do I call a Groovy script from Jenkins?

Visit “Manage Jenkins” > “Manage Nodes”. Select any node to view the status page. In the menu on the left, a menu item is available to open a “Script Console” on that specific agent. Scriptler allows you to store/edit groovy scripts and execute it on any of the slaves/nodes…

Is Jenkins script Groovy?

Jenkins features a Groovy script console which allows one to run arbitrary Groovy scripts within the Jenkins controller runtime or in the runtime on agents. It is very important to understand all of the following points because it affects the integrity of your Jenkins installation.

What is the use of Groovy hook script in Jenkins?

In several places inside Jenkins, a series of "hook scripts" get executed to allow some actions to take place in reaction to some key events. These scripts are written in Groovy, and get executed inside the same JVM as Jenkins, allowing full access to the domain model of Jenkins.


1 Answers

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)

like image 179
Jayan Avatar answered Sep 28 '22 14:09

Jayan