Search code examples
jenkinsgroovyjenkins-pipelinejenkins-groovy

Nested loops in Jenkinsfile


Fairly new to writing pipelines in Jenkins and can't seem to get past this particular issue. I wish to take 2 static lists and have each of the second list item appended to the first. Mostly I have succeeded in this but I don't seem to be able to find a method to remove the brackets from the second list item. Ultimately I will be breaking out the compile part into a separate library.

Many thanks in advance to anyone that can assist.

My code:

def food = ["eggs","chips"]
def drink =["water","juice","cola"]
def meal = []

    for (String fd : food){
        [drink].transpose().each {drinks ->
            meal.add("Food: ${fd}, Drinks: ${drinks}")}
    }

pipeline {
    agent any

    stages {
        stage('Results') {
            steps {
                echo 'Results'
                echo "${meal}"
            }
        }
    }
}

And the results (truncated)

Results
[Pipeline] echo
[Food: eggs, Drinks: [water], Food: eggs, Drinks: [juice], Food: eggs, Drinks: [cola], Food: chips, Drinks: [water], Food: chips, Drinks: [juice], Food: chips, Drinks: [cola]]
[Pipeline] }

As you can see from the results I have what I need except for not being able to remove the brackets


Solution

  • How about instead of using transpose, use something simpler:

    def meal = []
      food.each { item1 ->
        //println item1
        
        drink.each { item2 ->
          //println item2
          meal.add("Food: ${item1}, Drinks: ${item2}")
        }
      }