Search code examples
jenkinsgroovyjenkins-pipeline

How to convert a multi line string parameter to an array in jenkins declarative pipeline


I am trying to take a multi line string as input from user as parameter and trying to convert it to Array in Jenkins declarative pipeline.

I am stuck with this problem since 3 days.

I tried doing this:

    parameters ([
      text(defaultValue: '''
      A
      B
      C''', description: 'Enter alphabet in above format', 
       name: 'Alphabet'

def lines = "${Alphabet}"
def linesA = lines.toString.split('/n')

Any help will be highly appreciated.


Solution

  • The last line looks wrong. If you want to use toString(), you should add brackets at the end. The new line character begins with a backslash \n, not a slash. It should be

    def linesA =lines.toString().split('\n')
    

    Taking advantage of Groovy's default behavior, this can be shortened to

    def linesA =lines.split()
    

    Here is an example for the pipeline. Note that linesA here is a List of trimmed Strings:

    pipeline {
        agent any
    
        stages {
            stage('Read Alphabet') {
                input {
                    message "Alphabet"
                    parameters {
                        text(defaultValue: '''
          A
          B
          C''', 
                             description: 'Enter alphabet in above format', 
                             name: 'Alphabet')
                    }
                }
                steps {
                    script { 
                        def lines = "${Alphabet}"
                        def linesA = lines.split().collect { it.trim() }
                        echo "${linesA}"
                    }
                }      
            }
        }
    }