Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Loops in Jenkinsfiles
// Related to https://issues.jenkins-ci.org/browse/JENKINS-26481
abcs = ['a', 'b', 'c']
node('master') {
stage('Test 1: loop of echo statements') {
echo_all(abcs)
}
stage('Test 2: loop of sh commands') {
loop_of_sh(abcs)
}
stage('Test 3: loop with preceding SH') {
loop_with_preceding_sh(abcs)
}
stage('Test 4: traditional for loop') {
traditional_int_for_loop(abcs)
}
}
@NonCPS // has to be NonCPS or the build breaks on the call to .each
def echo_all(list) {
list.each { item ->
echo "Hello ${item}"
}
}
// outputs all items as expected
@NonCPS
def loop_of_sh(list) {
list.each { item ->
sh "echo Hello ${item}"
}
}
// outputs only the first item
@NonCPS
def loop_with_preceding_sh(list) {
sh "echo Going to echo a list"
list.each { item ->
sh "echo Hello ${item}"
}
}
// outputs only the "Going to echo a list" bit
//No NonCPS required
def traditional_int_for_loop(list) {
sh "echo Going to echo a list"
for (int i = 0; i < list.size(); i++) {
sh "echo Hello ${list[i]}"
}
}
// echoes everything as expected
@thiyagaraj

This comment has been minimized.

Copy link

@thiyagaraj thiyagaraj commented Sep 25, 2017

thank you! 👍

@timlevett

This comment has been minimized.

Copy link

@timlevett timlevett commented Oct 6, 2017

Yes! Exactly what I was looking for. Thanks

@Reesy

This comment has been minimized.

Copy link

@Reesy Reesy commented Jan 10, 2018

This has been extremely helpful, thank you!

@tamasgal

This comment has been minimized.

Copy link

@tamasgal tamasgal commented Apr 12, 2018

Thanks ;)

@prideloki

This comment has been minimized.

Copy link

@prideloki prideloki commented Apr 18, 2018

👍

@aliasmee

This comment has been minimized.

Copy link

@aliasmee aliasmee commented May 23, 2018

Thanks ^_^

@cropse

This comment has been minimized.

Copy link

@cropse cropse commented Oct 31, 2018

This is absolutely helpful, Thanks.

@juandrn

This comment has been minimized.

Copy link

@juandrn juandrn commented May 25, 2019

For me works with the last foreach and between script braces in pipeline:
Jenkisn version Jenkins ver. 2.164.3

SERVERDIRS = [ "%SERVERLINUXDIR%" , "%SERVERLINUXARMDIR%" ]

pipeline{
    environment {
		SERVERLINUXDIR		="Linux"
		SERVERLINUXARMDIR	="Linux-ARM"
    }
    stages	{
        stage ('Debug') {
            steps	{
				script{
					for (int i = 0; i < SERVERDIRS.size(); i++) {
						bat "echo Test Var ${SERVERDIRS[i]}"
					}
			      }
            }
    }
}
@nickboldt

This comment has been minimized.

Copy link

@nickboldt nickboldt commented Jun 6, 2019

.each also works in declarative pipeline like this, using a String[] rather than a List:

def platforms = "linux-x64,darwin-x64,linux-arm"
platforms.split(',').each {
	sh "echo Something something ${it} ..."
}
@vikepic

This comment has been minimized.

Copy link

@vikepic vikepic commented Jun 14, 2019

Thanks! 👍

@v1k-t0r

This comment has been minimized.

Copy link

@v1k-t0r v1k-t0r commented Jul 11, 2019

+1

@abgm

This comment has been minimized.

Copy link

@abgm abgm commented Jul 26, 2019

Thanks!!
fast connections check for different endpoints :)

node('master') {	
	stagesWithTry([
		'https://google.com/'
		,'https://github.com'
		,'https://releases.hashicorp.com/'
		,'https://kubernetes-charts.storage.googleapis.com'
		,'https://gcsweb.istio.io/gcs/istio-release/releases'
	])
}

def stagesWithTry(list){
	for (int i = 0; i < list.size(); i++) {
		try {	
			stage(list[i]){
					sh "curl --connect-timeout 15 -v -L ${list[i]}"
			} 
		} catch (Exception e) {
			echo "Stage failed, but we continue"  
		}
	}
}
@ansgarkroger

This comment has been minimized.

Copy link

@ansgarkroger ansgarkroger commented Nov 15, 2019

👍

@vinodkumar4b9

This comment has been minimized.

Copy link

@vinodkumar4b9 vinodkumar4b9 commented Jan 28, 2021

Hi All,

Nice one , But What If I need to read the values from a text file here , instead of putting that in an array , Any Help on this will be highly appreciated.

@nickboldt

This comment has been minimized.

Copy link

@nickboldt nickboldt commented Jan 28, 2021

https://stackoverflow.com/questions/20340688/reading-strings-from-a-file-and-putting-them-into-an-array-with-groovy ?

bear in mind though that some File method signatures are considered risky in Jenkins.

Or if you set up the array in a groovy file you can read it from a text file:

      sh('curl -sSLO https://raw.githubusercontent.com/redhat-developer/codeready-workspaces/crw-2-rhel-8/product/util.groovy')
      def util = load "${WORKSPACE}/util.groovy"
@vinodkumar4b9

This comment has been minimized.

Copy link

@vinodkumar4b9 vinodkumar4b9 commented Jan 29, 2021

Hi @nickboldt

Thanks for the Inputs on this , But It is not clearly working , let me tell you the Exact requirement which I am trying to achive.

Actually we have a text file where I have list of json Values (For E.g., ECS:repositoryname:Tagname) , So from that File I have already written a shell script to get All repository names in one text file and Tag names in another text file during the build, Till now Its working fine . But now I need to read the Tag values from that text file and need to clone that particular tag based on the repository values and then while cloning need to run the check-marx scan by using a single groovy command , So for that I need to read the values from the textfile and need to checkout the Repositories. For that I am trying different ways to read values from file , But I am unable to do it

Any help on this is Highly appreciated.

@vinodkumar4b9

This comment has been minimized.

Copy link

@vinodkumar4b9 vinodkumar4b9 commented Jan 29, 2021

Hi @abgm,

I have tried your script and Its working fine , But Instead of passing values in an array as you did , How can I read them from a file and print them .

@vinodkumar4b9

This comment has been minimized.

Copy link

@vinodkumar4b9 vinodkumar4b9 commented Feb 1, 2021

Hi All,

Actually I wanted to read files from Text file and wanted to Iterate the same in for loop and print values one by one , Any Suggestions on this is highly appreciated as I have spend so much time on this , But still couldnt find out , I an able to read the values but not able to print them using for loop

Sharing the code below for refernce

pipeline {
agent any
stages {
stage('Example') {
steps {

            script {
                def browsers =   readFile(file: 'repos.txt') 
                def lines = browsers.readLines()
                
                for (int i = 0; i < lines.size(); ++i) {
                    
                    echo "${lines}"
                }
            }
        }
    }
}

}

getting different outputs lets say getting all values at a time five times as size of file is five words , But I need one by one only one at a time in for loop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment