Jenkins and Groovy Scripts

Jenkins and Groovy Scripts

Jenkins provides the option to run Groovy scripts, which makes it really easy to customize everything about Jenkins or even its plugins.

You can run a Groovy script as a build step or as a post build step. There is a wonderful Groovy Postbuild plugin that you can use to tweak anything in the build. As an admin you can also access the Script Console under the Manage Jenkins page to run any arbitrary script. If you need to remove a number of build under a job based on a condition, you can fire up your script here and get the job done in seconds.

Perhaps, the most important thing to realize is that, you can now refer to the Jenkins documentation and access the API via Groovy scripts.

Head over to the Script Console, and fire up the below script:

def job = Jenkins.instance.getItemByFullName(‘MY_JOB_NAME’)
println job.builds

When you run getItemByFullName, you will get a reference to a Job object. And by referring to the documentation, we can run any methods on it. getBuilds() is one such method and since its groovy, the getter can be called directly as builds. So job.getBuilds() is the same as job.builds.

To access the last build, run

def lastBuild = job.lastBuild

If you are running the script on the build, and not in the console, you may need to access the current ongoing build. To do that, run below as a build step or post build script.

def thr = Thread.currentThread()
def currentJob = thr?.executable

You can even perform actions by checking if some plugins are in use. For example, if you need to check if the Maven release plugin is running and is not a dry run, below script should help:

for (def action : currentJob.actions) {
    if (action.getClass() == org.jvnet.hudson.plugins.m2release.M2ReleaseArgumentsAction && !action.isDryRun()) {
      println 'Maven release, not a dry run'

If you need to access the archived files of a job, accessing the Artifact Manager is easy.

new File(lastBuild.getArtifactManager().root().toURI()).eachFileRecurse( {archivedFile->

Your current workspace can be accessed by currentJob.workspace. If you need to create a temporary folder inside the workspace, try below:

String tempFolderPath = currentJob.workspace.createTempDir("tempFolder", null).getRemote()

The Groovy Postbuild plugin provides a manager object which can be used to do a number of useful things as explained in plugin documentation.

The script below puts a warning badge and mark the build as unstable if it detects that deprecated methods were used.

if(manager.logContains(".*uses or overrides a deprecated API.*")) {
    manager.addWarningBadge("Thou shalt not use deprecated methods.")
    manager.createSummary("warning.gif").appendText("<h1>You have been warned!</h1>", false, false, false, "red")

More examples are provided in the plugin page.

Leave a Reply

Your email address will not be published. Required fields are marked *