Jenkins Pipeline - loop over multi string variable with groovy

7,536 views
Skip to first unread message

John

unread,
Apr 4, 2018, 5:46:15 PM4/4/18
to Jenkins Users
I'm trying to loop over a var that contains multiple strings (file paths), and then run a shell script against each one. But for some reason everything i try loops over every single letter of the string. Here is my code:

def call(Map config) {

  node('terraform-slave') {
    cleanWs()
    checkout scm

    stage('Plan') {
      commitChangeset = sh(returnStdout: true, script: 'git diff-tree --no-commit-id --name-only -r HEAD').trim()
    }
    stage('EchoToVerify') {
      tfvars = commitChangeset.replaceAll("terraform.tfvars", "")
      echo tfvars
    }
    stage('Loop') {
      loop(tfvars)
    }
  }
}

def loop(list) {
  list.each {
    sh "(cd ${it}; cat terraform.tfvars)"
  }
}



If you see the EchoToVerify stage, that works fine. Multiple file paths are echo'ed, like so:

/file/to/dir1
/file/to/dir2
/file/to/dir3

But when the Loop starts, it loops against each letter.. f, i, l, e, etc....

The only way I have been able to get it work is is by doing this:

def loop(list) {
  for (dir in [list]) {
    sh "(cd ${it}; cat terraform.tfvars)"
  }
}

However it only works when there is one value in the variable. It seems to want to iterate over ${it} immediately, before going to the next shell command (cat terraform.tfvars). It seems like it tries to "cd" to the next directory immediately.

Thanks for the help!




Viacheslav Dubrovskyi

unread,
Apr 25, 2018, 10:31:14 AM4/25/18
to jenkins...@googlegroups.com

Hi

commitChangeset = sh( ... ).trim() will return string. You should transform it to list, for example:

commitChangeset = sh( ... ).trim().tokenize(",") where delimiter is ","

And then no need to replace "," by " " in

tfvars = commitChangeset.replaceAll("terraform.tfvars", "")

And then you can use cycle for iterate list:
for (int i = 0; i < commitChangeset.size() ; i++) {
    int index=i
    sh "(cd ${commitChangeset[index]}; etc... )"
}



05.04.2018 00:24, John пишет:
--
You received this message because you are subscribed to the Google Groups "Jenkins Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jenkinsci-use...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/jenkinsci-users/3b411f4a-56f4-4c04-a9a4-6fde13f2239e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

-- 
WBD,
Viacheslav Dubrovskyi

Justin Zhang

unread,
Jul 29, 2018, 10:56:21 PM7/29/18
to Jenkins Users
Hi Slava,

I tried your way, found that the iteration of command only works on  the first loop,

For the second loop, it only execute the string. not the command with the string.

Not sure if you have a way to fix it ?


在 2018年4月26日星期四 UTC+10上午12:31:14,Slava Dubrovskiy写道:
Reply all
Reply to author
Forward
0 new messages