41

I have a parameterized job that uses the Perforce plugin and would like to retrieve the build parameters/properties as well as the p4.change property that's set by the Perforce plugin.

How do I retrieve these properties with the Jenkins Groovy API?

11 Answers 11

35

Update: Jenkins 2.x solution:

With Jenkins 2 pipeline dsl, you can directly access any parameter with the trivial syntax based on the params (Map) built-in:

echo " FOOBAR value: ${params.'FOOBAR'}"

The returned value will be a String or a boolean depending on the Parameter type itself. The syntax is the same for scripted or declarative syntax. More info at: https://jenkins.io/doc/book/pipeline/jenkinsfile/#handling-parameters

If your parameter name is itself in a variable:

def paramName = "FOOBAR"
def paramValue = params.get(paramName) // or: params."${paramName}"
echo """ FOOBAR value: ${paramValue}"

Original Answer for Jenkins 1.x:

For Jenkins 1.x, the syntax is based on the build.buildVariableResolver built-ins:

// ... or if you want the parameter by name ...
def hardcoded_param = "FOOBAR"
def resolver = build.buildVariableResolver
def hardcoded_param_value = resolver.resolve(hardcoded_param)

Please note the official Jenkins Wiki page covers this in more details as well, especially how to iterate upon the build parameters: https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+System+Groovy+script

The salient part is reproduced below:

// get parameters
def parameters = build?.actions.find{ it instanceof ParametersAction }?.parameters
parameters.each {
   println "parameter ${it.name}:"
   println it.dump()
}
5
  • This is failing with "groovy.lang.MissingPropertyException: No such property: build for class: WorkflowScript" Any idea?. Most probably build parameter is not accessible while running parameterized jenkins job with groovy pipeline.
    – Krishnom
    Jul 11, 2019 at 4:54
  • This (old) answer applies for a Jenkins 1.x service, while you've likely tried it in a Jenkins 2.x env, via a Jenkinsfile ?
    – Patrice M.
    Jul 11, 2019 at 16:26
  • I am trying to access in a groovy pipeline. But i found the solution (thanks to the clue in your answer). there is a "params" global that i used to retrieve build parameter map.
    – Krishnom
    Jul 17, 2019 at 1:44
  • Can you please elaborate. I am too kind of stuck here."groovy.lang.MissingPropertyException: No such property: build for class: WorkflowScript"
    – dgupta3091
    Oct 18, 2019 at 16:28
  • 1
    Again, I'm pretty sure this only works with the old Jenkins 1.x with the Parameterized Groovy Script plugin, but not with Jenkins 2.x. For the latter, you can replace the whole script with: def value = params.'FOOBAR' . It is essentially directly supported by the pipeline groovy syntax.
    – Patrice M.
    Oct 18, 2019 at 20:40
27

For resolving a single parameter (I guess what's most commonly needed), this is the simplest I found:

build.buildVariableResolver.resolve("myparameter")

in your Groovy System script build step.

3
  • 6
    This results in groovy.lang.MissingPropertyException: No such property: build for class: Script1
    – dokaspar
    Nov 16, 2016 at 9:39
  • @dokaspar Because this work for groovy script plugin
    – old-monk
    Jan 23, 2018 at 23:21
  • if your groovy is a class, how do you do this? Sep 20, 2018 at 20:47
21

Regarding parameters:

See this answer first. To get a list of all the builds for a project (obtained as per that answer):

project.builds

When you find your particular build, you need to get all actions of type ParametersAction with build.getActions(hudson.model.ParametersAction). You then query the returned object for your specific parameters.

Regarding p4.change: I suspect that it is also stored as an action. In Jenkins Groovy console get all actions for a build that contains p4.change and examine them - it will give you an idea what to look for in your code.

10

I've just got this working, so specifically, using the Groovy Postbuild plugin, you can do the following:

def paramText
def actionList = manager.build.getActions(hudson.model.ParametersAction)
if (actionList.size() != 0)
{
  def pA = actionList.get(0)
  paramText = pA.createVariableResolver(manager.build).resolve("MY_PARAM_NAME")
}
0
6

In cases when a parameter name cannot be hardcoded I found this would be the simplest and best way to access parameters:

def myParam = env.getProperty(dynamicParamName)

In cases, when a parameter name is known and can be hardcoded the following 3 lines are equivalent:

def myParam = env.getProperty("myParamName")
def myParam = env.myParamName
def myParam = myParamName
1
  • 1
    I was looking for getting a dynamic param, env.getProperty worked. Thanks.
    – Mahesh
    Aug 20, 2018 at 6:36
3

To get the parameterized build params from the current build from your GroovyScript (using Pipeline), all you need to do is: Say you had a variable called VARNAME.

def myVariable = env.VARNAME

2

Get all of the parameters:

System.getenv().each{
  println it
}

Or more sophisticated:

def myvariables = getBinding().getVariables()
for (v in myvariables) {
   echo "${v} " + myvariables.get(v)
}

You will need to disable "Use Groovy Sandbox" for both.

2
  • the later one doesn't work for me, I am getting an empty array
    – old-monk
    Jan 23, 2018 at 23:28
  • Do you know how I may set it though? I can write up a new question for you to answer
    – old-monk
    Jan 23, 2018 at 23:33
2

thanks patrice-n! this code worked to get both queued and running jobs and their parameters:

import hudson.model.Job
import hudson.model.ParametersAction
import hudson.model.Queue
import jenkins.model.Jenkins

println("================================================")
for (Job job : Jenkins.instanceOrNull.getAllItems(Job.class)) {
    if (job.isInQueue()) {
        println("------------------------------------------------")
        println("InQueue " + job.name)

        Queue.Item queue = job.getQueueItem()
        if (queue != null) {
            println(queue.params)
        }
    }
    if (job.isBuilding()) {
        println("------------------------------------------------")
        println("Building " + job.name)

        def build = job.getBuilds().getLastBuild()
        def parameters = build?.getAllActions().find{ it instanceof ParametersAction }?.parameters
        parameters.each {
            def dump = it.dump()
            println "parameter ${it.name}: ${dump}"
        }
    }
}
println("================================================")
2

If you are trying to get all parameters passed to Jenkins job you can use the global variable params in your groovy pipeline to fetch it.

http://jenkins_host:8080/pipeline-syntax/globals

params

Use something like below.

def dumpParameter()
{
  params.each {
    println it.key + " = " + it.value
  }
}
1

The following snippet worked for me to get a parameter value in a parameterized project:
String myParameter = this.getProperty('binding').getVariable('MY_PARAMETER')

The goal was to dynamically lock a resource based on the selected project parameter.

In "[✓] This build requires lockable resources" I have the following "[✓] Groovy Expression":

if (resourceName == 'resource_lock_name') {
    Binding binding = this.getProperty('binding')
    String profile = binding.getVariable('BUILD_PROFILE')

    return profile == '-Poradb' // acquire lock if "oradb" profile is selected
}

return false

In "[✓] This project is parameterized" section I have a "Choice Parameter" named e.g. BUILD_PROFILE Example of Choices are:

-Poradb
-Ph2db
-DskipTests -T4

The lock on "resource_lock_name" will be acquired only if "-Poradb" is selected when building project with parameters

[-] Use Groovy Sandbox shall be unchecked for this syntax to work

0

The following can be used to retreive an environment parameter:

println System.getenv("MY_PARAM") 
1
  • IIRC, the Groovy script is run on the master, not the slave. Things may have changed since I asked the original question, though.
    – Noel Yap
    Sep 16, 2019 at 18:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.