jenkinsdeclarative

How to use for loop with def list in Jenkins declarative pipeline


I have used for-loop in my script to run one by one which is mentioned in def data it is executing in how many values are given in def data but inside def data the word in not picking and not applying to the sentence.

Help me to slove this issue that help me to slove the original issue

Example

Def data = [ "apple","orange" ]

Stage(create sentence){

Steps{

Script {

For (x in data){

 Sh 'the fruit name is ${x}

}

}

}

}

Excepted output

  1. the fruit name is apple

  2. the fruit name is orange

But my output be like

  1. the fruit name is

  2. the fruit name is


Solution

  • To use loop in this case you don't need for, you can simply iterate in the list you have.

    To iterate only value:

    data.each{
            println it
        }
    

    OR

    data.each {val-> 
                 println(val)
              }
           
    

    To iterate Value with index:

    data.eachWithIndex{it,index->
                println "value " + it + " at index " +index
        }
    

    So, final pipeline looks like this.

    def data = [ "apple","orange" ] 
    pipeline {
        agent any
       
        stages 
        {
            stage('create sentence') 
            {
                steps 
                {
                    script{
                    data.each {val->  
                             println("the fruit name is " + val)
                          }
                    }
           
                }
            }
            
        }
    }