Iterating a groovy list in Jenkins Pipeline DSL

2019-07-04 03:48发布

问题:

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:

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.