6
votes

I have a simple groovy list in my Pipeline that adds some maps:

def componentList = []

def componentMapEntry1 = [:]
componentMapEntry1['componentName']="Dashboard_Core"
componentList << componentMapEntry1

def componentMapEntry2 = [:]
componentMapEntry2['componentName']="Dashboard_Equities"
componentList << componentMapEntry2

def cme3 = [:]
cme3["componentName"] = "home"
componentList << cme3

When job is executed, I validate size

echo "size of list "+componentList.size()

...

[Pipeline] echo
size of list 3

I can print it out the list

println componentList

...

[Pipeline] echo
[{componentName=Dashboard_Core}, {componentName=Dashboard_Equities}, {componentName=home}]

I can do a for loop and iterate the list

for (i = 0; i <componentList.size(); i++) {
    println componentList[i]
}

...

[Pipeline] echo
{componentName=Dashboard_Core}
[Pipeline] echo
{componentName=Dashboard_Equities}
[Pipeline] echo
{componentName=home}

So far all's well.

Problem comes in when I try to use standard groovy iterator:

componentList.each {
    println "adding "+it.componentName
}

In this case I only get the first element

[Pipeline] echo
adding Dashboard_Core

Why would I only get the first element here? I've tried this several times and using .each() only seems to return first element. When I run the same code at groovy command line, it naturally iterates as groovy would expect. Is the .each{ } function getting overwritten somehow?

1
I doubt it... does: [[componentName:'Dashboard_Core'], [componentName:'Dashboard_Equities'], [componentName:'home']].each { println "adding $it.componentName" } work as expected? What about ['Dashboard_Core', 'Dashboard_Equities', 'home'].collect { [componentName: it] }.each { println "adding $it.componentName" }?tim_yates
First one does not, it only shows the first element as mine did. Second one fails in the sandbox environment: org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified field java.util.LinkedHashMap$Entry componentNameNeil
How old is the version of groovy on your servers? My money is on ancient...tim_yates
I am pretty sure Pipeline uses the built-in groovy library for Jenkins. We are running Jenkins 1.642.3Neil

1 Answers

8
votes

The each method on a closure does not yet work in Pipeline script. A fix is in progress. Meanwhile use a C-style for loop.