Storing list of values in the environment variable in declarative Jenkins pipeline
The declarative pipeline comes with some limitations if it comes to its syntax. You see this error because in the environment
block you can assign only two types of expressions:
- strings (single or double quoted)
- values returns from function calls
However, you need to be aware that the environment variables store only string values, so if you return an array (or any other type from) from the function call, it will be automatically converted to its toString()
representation.
pipeline { agent any environment { MYPODS = getPods() } stages { stage("Test") { steps { script { println "My pods = ${env.MYPODS}" } } } }}def getPods() { return ['pod1', 'pod2']}
Console output:
[Pipeline] node[Pipeline] {[Pipeline] withEnv[Pipeline] {[Pipeline] stage[Pipeline] { (Test)[Pipeline] script (hide)[Pipeline] {[Pipeline] echo<java.lang.String@ed6c7b35 value=[pod1, pod2] hash=-311657675>[Pipeline] echoMYPODS = [pod1, pod2][Pipeline] echoItem: [[Pipeline] echoItem: p[Pipeline] echoItem: o[Pipeline] echoItem: d[Pipeline] echoItem: 1[Pipeline] echoItem: ,[Pipeline] echoItem: [Pipeline] echoItem: p[Pipeline] echoItem: o[Pipeline] echoItem: d[Pipeline] echoItem: 2[Pipeline] echoItem: ][Pipeline] }[Pipeline] // script[Pipeline] }[Pipeline] // stage[Pipeline] }[Pipeline] // withEnv[Pipeline] }[Pipeline] // node[Pipeline] End of PipelineFinished: SUCCESS
Solution
If you want to store a list of string values then you can define it as a single string of values delimited with ,
character. In this case you can simply tokenize it to a list of values. Consider the following example:
pipeline { agent any environment { MYPODS = 'pod1,pod2,pod3' } stages { stage("Test") { steps { script { MYPODS.tokenize(',').each { println "Item: ${it}" } } } } }}
Output:
[Pipeline] node[Pipeline] {[Pipeline] withEnv[Pipeline] {[Pipeline] stage[Pipeline] { (Test)[Pipeline] script[Pipeline] {[Pipeline] echoItem: pod1[Pipeline] echoItem: pod2[Pipeline] echoItem: pod3[Pipeline] }[Pipeline] // script[Pipeline] }[Pipeline] // stage[Pipeline] }[Pipeline] // withEnv[Pipeline] }[Pipeline] // node[Pipeline] End of PipelineFinished: SUCCESS
your environment should be after the agent
pipeline {agent anyenvironment { def mypods = []}stages { stage('Getting pods') { steps { script { withKubeConfig(caCertificate: '.....', credentialsId: '.....', serverUrl: '.....') { env.mypods = sh "kubectl get pod | grep Running | awk '{print \$1}'" } } } } stage('Print pods') { steps { script { mypods.each { println "Item: $it" } } } }}
}