In Jenkins declarative pipeline: failure to iterate through list in for loop

59 views Asked by At

I'm trying to understand what is happening here in Jenkins pipeline script. I have this code which is taking a list of values (originally strings but changed to try to simplify/troubleshoot), iterating through the list, storing each value into a variable and outputting :

def CURR_VER
def NFS_VERS = [2, 3, 4, 4.1]

for (i in env.NFS_VERS) {
    env.CURR_VER = i
    echo env.CURR_VER
}

When it runs, Jenkins log shows that the echo outputs not just the values but the brackets, commas, etc. too (see screenshot).

Jenkins output

Tried changing the format of the for loop but nothing seems to resolve it.

1

There are 1 answers

0
Alexander Pletnev On

You are iterating over the environment variable env.NFS_VERS, not over the original list NFS_VERS that is defined. In pipelines (but not in Multibranch pipelines!) Jenkins automatically propagates the Groovy variables into the environment variables, but they are always interpreted as strings. So your script just takes a string and echoes every its character.

Try this:

def CURR_VER
def NFS_VERS = [2, 3, 4, 4.1]

for (i in NFS_VERS) {
    env.CURR_VER = i
    echo env.CURR_VER
}

In multibranch pipelines the same script as yours will print nothing because env.NFS_VERS would be null.

Also, if you will ever need to print something into a build log, I'd recommend using println instead of echo so that the log is not clogged with additional command names.