Jenkins & Groovy – accessing build parameters

We’re using Jenkins version 1.651 with the Groovy plugin for Jenkins version 1.4.

I had real trouble getting access to the build parameters when trying to run a groovy script build step using the recommended methods of which there are many.

From the plugin documentation:

// Retrieve parameters of the current build
def foo = build.buildVariableResolver.resolve("FOO")
println "FOO=$foo"

This doesn’t work.

From Jenkins help:

def thr = Thread.currentThread()
 def build = thr.executable
 // get build parameters
 def buildVariablesMap = build.buildVariables
 // get all environment variables for the build
 def buildEnvVarsMap = build.envVars
String jobName = buildEnvVarsMap?.JOB_NAME

This also doesn’t work but I believe that’s because the groovy script isn’t running in the same process as the Jenkins job (or so I’ve heard).

I also tried the Jenkins wiki that suggested:

import hudson.model.*

// get current thread / Executor
def thr = Thread.currentThread()
// get current build
def build = thr?.executable

// get parameters
def parameters = build?.actions.find{ it instanceof ParametersAction }?.parameters
parameters.each {
   println "parameter ${it.name}:"
   println it.dump()
   println "-" * 80
}
// ... or if you want the parameter by name ...
def hardcoded_param = "FOOBAR"
def resolver = build.buildVariableResolver
def hardcoded_param_value = resolver.resolve(hardcoded_param)

println "param ${hardcoded_param} value : ${hardcoded_param_value}"

 

So, to the solution…

import hudson.model.*
def foobar = System.getenv("FOOBAR")

It’s so simple it’s painful.

Advertisements

2 thoughts on “Jenkins & Groovy – accessing build parameters

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s