Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the current Jenkins build in Groovy script

Tags:

jenkins

groovy

I have created a Groovy script which is used in a System Groovy Script step in a Jenkins job which needs to access the current build of the current job.

The current build is required when using an Hudson.model Cause.UpstreamCause to link the current build of my current job to a dependent job that I am scheduling.

Since code is more concise:

my-job-step.groovy:

def scheduleDependentJob(jobName) {
  def fooParam = new StringParameterValue('foo', 'bar');
  def paramsAction = new ParametersAction(fooParam)

  println "Scheduling dependent job"
  def currentJob = ???
  def cause = new Cause.UpstreamCause(currentBuild)
  def causeAction = new hudson.model.CauseAction(cause)
  instance.queue.schedule(job, 0, causeAction, paramsAction)
}

The CauseAction constructor (Seen on http://javadoc.jenkins-ci.org/hudson/model/Cause.UpstreamCause.html) requires a Run object, which the current build object should be an instance of. I just can't find a good way to get the current running job build inside of a Groovy script.

like image 256
Ian Marcinkowski Avatar asked Apr 12 '16 18:04

Ian Marcinkowski


People also ask

How do I run a Jenkins Groovy script?

Usage. To create Groovy-based project, add new free-style project and select "Execute Groovy script" in the Build section, select previously configured Groovy installation and then type your command, or specify your script file name. In the second case path taken is relatively from the project workspace directory.

How do I view Jenkins script?

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.


1 Answers

If in your Jenkins job you are using Groovy plug-in, then inside Execute system Groovy script step the plug-in already provides you access to some predefined variables:

build
    The current AbstractBuild.
launcher
    A Launcher.
listener
    A BuildListener.
out
    A PrintStream (listener.logger).

For example:

println build.getClass()

Outputs:

class hudson.model.FreeStyleBuild
like image 154
luka5z Avatar answered Oct 07 '22 07:10

luka5z