Search code examples
groovyjenkins-pipelinejenkins-groovygroovydsl

Jenkinsfile with string variable issue


I have a Jenkinsfile and parsing list of ports from input file,

pipeline {
  parameters {
    string(defaultValue: '4000', name: 'Port', trim: true)
  }
  
  stage('Test') {
    steps {
      script {
        echo 'Testing..'
        script {
          def data = readFile(file: 'list.txt')
          println(data)
          def Port = ""
          data.eachLine { line ->
            def arr = line.tokenize('\t')
            println "port: ${arr[0]}}"   # Prints values
            println "port: arr[0]"         # Prints name of Varible
            build quietPeriod: 2,
            job: 'Downstream_Jenkinsfile_Job',
            parameters: [string(name: 'Port', value: ${arr[0]})]  # <- ERROR HERE
          }
        }
      }
    }
  }
}

The line parameters: [string(name: 'Port', value: ${arr[0]})] gives error

[Pipeline] End of Pipeline
java.lang.NoSuchMethodError: No such DSL method '$' found among steps [archive,
...
at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:23)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:157)

I tried with:
parameters: [string(name: 'Port', value: ${arr[0]}]
parameters: [string(name: 'Port', value: arr[0]]

What is causing the issue ? I typecasted and no luck. Thanks


Solution

  • It has to be

    build quietPeriod: 2,
                job: 'Downstream_Jenkinsfile_Job',
                parameters: [string(name: 'Port', value: "${arr[0]}")]
    

    a pipeline can interpolate the value if $ is with in "" and on your example you left the parameter value ${arr[0]} but it has to be like "${arr[0]}"