groovy 在声明性Jenkins管道中存储环境变量中的值列表

63lcw9qa  于 2022-11-01  发布在  Jenkins
关注(0)|答案(3)|浏览(283)

我有下面的管道,但我不知道为什么它在第一行代码上失败:

pipeline {
    agent any
    environment {
        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"
                    }
                }
            }
        }
    }
}

我需要使用一个列表,因为kubectl get pod命令返回了一个pod列表,所以我必须在各个阶段保存和使用它们。我如何在声明性管道上创建一个列表?提前感谢。
这是错误:

Running in Durability level: MAX_SURVIVABILITY
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 4: Environment variable values must either be single quoted, double quoted, or function calls. @ line 4, column 22.
           def mypods = []
                        ^

WorkflowScript: 3: No variables specified for environment @ line 3, column 5.
       environment {
       ^

2 errors

    at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
    at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
    at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:131)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:125)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:560)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:521)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:320)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE
r1zhe5dt

r1zhe5dt1#

声明性管道在语法方面有一些限制。之所以出现此错误,是因为在environment块中,只能分配两种类型的表达式:

  • 字符串(单引号或双引号)
  • 从函数调用返回的值

但是,您需要注意,环境变量仅存储字符串值,因此,如果您从函数调用返回数组(或任何其他类型),它将自动转换为toString()表示形式。

pipeline {
    agent any 

    environment {
        MYPODS = getPods()
    }

    stages {
        stage("Test") {
            steps {
                script {
                    println "My pods = ${env.MYPODS}"
                }
            }
        }
    }
}

def getPods() {
    return ['pod1', 'pod2']
}

控制台输出:

[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] echo
MYPODS = [pod1, pod2]
[Pipeline] echo
Item: [
[Pipeline] echo
Item: p
[Pipeline] echo
Item: o
[Pipeline] echo
Item: d
[Pipeline] echo
Item: 1
[Pipeline] echo
Item: ,
[Pipeline] echo
Item:  
[Pipeline] echo
Item: p
[Pipeline] echo
Item: o
[Pipeline] echo
Item: d
[Pipeline] echo
Item: 2
[Pipeline] echo
Item: ]
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

溶液

如果要存储字符串值列表,则可以将其定义为以,字符分隔的单个值字符串。在这种情况下,只需将其标记为值列表即可。请考虑以下示例:

pipeline {
    agent any 

    environment {
        MYPODS = 'pod1,pod2,pod3'
    }

    stages {
        stage("Test") {
            steps {
                script {
                    MYPODS.tokenize(',').each {
                        println "Item: ${it}"
                    }
                }
            }
        }
    }
}

输出量:

[Pipeline] node
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Item: pod1
[Pipeline] echo
Item: pod2
[Pipeline] echo
Item: pod3
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
edqdpe6u

edqdpe6u2#

您的环境应该在代理之后

pipeline {

agent any
environment {
    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"
                }
            }
        }
    }
}

}

qni6mghb

qni6mghb3#

您也可以使用.split(“,”)函数和for-in循环进行迭代。

pipeline {
agent any 

environment {
    MYPODS = 'pod1,pod2,pod3'
}

stages {
    stage("Test") {
        steps {
            script {
              for (pod in MYPODS.split(",")) {
                  println("${pod}")
               }
            }
        }
    }
}

}

相关问题