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?

Noel Yap
  • 18,822
  • 21
  • 92
  • 144

11 Answers11

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()
}
Patrice M.
  • 4,209
  • 2
  • 27
  • 36
  • 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 '19 at 04: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 '19 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 '19 at 01: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 '19 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 '19 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.

inger
  • 19,574
  • 9
  • 49
  • 54
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.

Community
  • 1
  • 1
malenkiy_scot
  • 16,415
  • 6
  • 64
  • 87
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")
}
Dan
  • 101
  • 1
  • 3
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
ATrubka
  • 3,982
  • 5
  • 33
  • 52
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

XP84
  • 1,236
  • 2
  • 11
  • 15
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.

Atais
  • 10,857
  • 6
  • 71
  • 111
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
  }
}
Krishnom
  • 1,348
  • 12
  • 39
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("================================================")
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

JavaExcel
  • 21
  • 1
0

The following can be used to retreive an environment parameter:

println System.getenv("MY_PARAM") 
MaartenDev
  • 5,631
  • 5
  • 21
  • 33
  • 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 '19 at 18:12