How to define Groovy text array using a parameter?

Hi, I want to set a Groovy variable, which defines an array of strings, using a parameter.

parameters {
      text defaultValue: 'file1.txt,\nfile2.txt,\nfile3.txt,\nfile4.txt',
      name: 'filenames', 
}

stage('exp') {
    steps {
        script {
        //def files = ['file1.txt', 'file2.txt', 'file3.txt', 'file4.txt']
        def files = params.filenames

        for (file in files) {
             echo "Preparing $file"
        }
    }
}

This isn’t working. In the ‘for’ loop, variable ‘file’ just contains one character, not an entire filename.

What would be the correct syntax please?

There is no parameter that will return an array to my knowledge. But you can just split the parameter at the line breaks (do not include the commas in the default)

parameters {
      text defaultValue: 'file1.txt\nfile2.txt\nfile3.txt\nfile4.txt',
      name: 'filenames', 
}

stage('exp') {
    steps {
        script {
        //def files = ['file1.txt', 'file2.txt', 'file3.txt', 'file4.txt']
        def files = params.filenames.split('\n')

        for (file in files) {
             echo "Preparing $file"
        }
    }
}

Thank you Markus. That worked nicely.

@mawinter69 For freestyle jobs, active choice parameters return array lists. Can they be used in a pipeline job for this purpose?

Active choice can be used in pipeline, but configuration is a pain at the moment due to missing symbols (see Add @Symbol to support pipeline by kinow · Pull Request #80 · jenkinsci/active-choices-plugin · GitHub). But normally parameters are passed as environment variables in freestyle jobs so I wonder how should they be used when there is an array. The active choice plugin unfortunately doesn’t explain how to e.g. a mutliselect parameter can be used in a pipeline.
Also in this context here I think the requirement is to allow the user to enter arbitrary values and not choose from a list of predefined values

1 Like

taking a closer look at the sources, active choice is also just returning a string and not an array.

1 Like

Thank you for your important (and correct!) points @mawinter69 about Active Choices. The AC groovy script has to return a list or a map, which is turned into a comma delimited parameter string, when the user makes multiple selections. I think it would be relatively trivial to split this string to create an array. Nonetheless, having multiple options to do something is always the strength of Jenkins.