Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy .each only iterates one time

The script is not iterating through all the values of the 'modules' array.

class Module {
    public String name = '';
    public Boolean isCustom = false;
    public Module(String name, Boolean custom){
        this.name = name;
        this.isCustom = custom;
    }
}

//creates array from the ext_module env var
modules = [];
EXT_MODULE.split(',').each { 
    modules.add(new Module(it, false));
}


println modules;
modules.each {  
    println "MODULE NAME ::::: ${it.name}"
    if(it.isCustom)
    {
        println "install custom";
    } else {
        println "install non custom";
    }
};

This is the result of the run. The array shows 4 elements, but the code inside the .each black only executes once.

Running: Print Message [Module@71f09325, Module@e1ddb41, Module@7069a674, Module@1f68f952]
Running: Print Message MODULE NAME ::::: puppetlabs-ntp
Running: Print Message install non custom
Running: End of Workflow
Finished: SUCCESS

like image 571
Nicholas Smith Avatar asked Dec 16 '14 16:12

Nicholas Smith


2 Answers

The messages "Running: Print Message" and "Running: End of Workflow" indicate that you are using the new workflow plugin: https://wiki.jenkins-ci.org/display/JENKINS/Workflow+Plugin. This plugin currently has a bug causing at least some Groovy iterations involving a closure to be aborted after one iteration: https://issues.jenkins-ci.org/browse/JENKINS-26481

like image 185
dtschan Avatar answered Sep 18 '22 12:09

dtschan


The workaround is to simply use an old school for loop (code below). Also, NonCPS is another workaround. There is an open issue for this matter. See here: https://issues.jenkins-ci.org/browse/JENKINS-26481

Update, Oct 24th, 2016

/** * Dumps environment varibles to the log, using an old school for loop. */

import com.cloudbees.groovy.cps.NonCPS

def version = '1.0'

@NonCPS
def dumpEnvVars() {
  def str = "Dumping build environment variables...\n"
  for (Map.Entry<String, String> entry : currentBuild.build().environment) {
    str += "    ${entry.key} = ${entry.value}\n"
  }
  echo str
}

return this;
like image 42
Sam Avatar answered Sep 20 '22 12:09

Sam