【问题标题】:Value returned from a script does not assigned to a variable declared in jenkins declarative pipeline stage从脚本返回的值未分配给在 jenkins 声明性管道阶段声明的变量
【发布时间】:2020-03-17 05:28:03
【问题描述】:

我正在为自动化测试添加一个 jenkins 声明式管道。在测试运行阶段,我想从日志中提取失败的测试。我正在使用 groovy 函数来提取测试结果。此功能不是詹金斯管道的一部分。这是另一个脚本文件。该函数工作正常,它构建了一个包含故障详细信息的字符串。在管道阶段,我正在调用此函数并将返回的字符串分配给另一个变量。但是当我回显变量值时,它会打印空字符串。

pipeline {
    agent {
        kubernetes {
            yamlFile 'kubernetesPod.yml'
        }
    }
    environment{
        failure_msg = ""
    }
    stages {
        stage('Run Test') {
            steps {
                container('ansible') {
                    script {
                        def notify = load('src/TestResult.groovy')
                        def result = notify.extractTestResult("${WORKSPACE}/testreport.xml")
                        sh "${result}"
                        if (result != "") {
                            failure_msg = failure_msg + result
                        }
                    }

                }  
            }
        }
    post {
        always {
            script {
                sh 'echo Failure message.............${failure_msg}'
                }
        }
    }
}

这里 'sh 'echo ${result}'' 打印空字符串。但是 'extractTestResult()' 返回一个非空字符串。

我也不能在帖子部分使用环境变量“failure_msg”,它返回一个错误'groovy.lang.MissingPropertyException: No such property: failure_msg for class: groovy.lang.Binding'

谁能帮我解决这个问题?

编辑:

即使在我修复了字符串插值之后,我也得到了相同的结果 错误。那是因为詹金斯不允许在里面使用'sh' 码头集装箱。 jenkins issue board 中有一个开放的 bug 票

【问题讨论】:

  • 如果您在 sh-command 上使用正确的字符串插值 (jenkins.io/doc/book/pipeline/jenkinsfile/#string-interpolation),您能否尝试一下如果您的问题消失了。试试: sh "${failure_msg}"
  • 另一个问题可能是该变量在 post-stage-scope 中不存在,因为它是在 steps-block 的范围内声明的。
  • 同意@mkemmerz。这是不正确的字符串插值。另外,这里的failure_msg不是设置为环境变量,而是Groovy全局变量。不同之处在于环境变量 (env.failure_msg) 可用于管道脚本调用的子 shell,而 Groovy 全局变量则不可用。在对 sh 使用双引号时,是 Groovy 插入变量而不是 shell。

标签: jenkins groovy jenkins-pipeline jenkins-declarative-pipeline


【解决方案1】:

我建议使用全局变量来保存错误消息。我的猜测是该变量在您的范围内不存在。

def FAILURE_MSG // Global Variable

pipeline {
    ...
    stages {
        stage(...
            steps {
                container('ansible') {
                    script {
                        ...
                        if (result != "") {
                            FAILURE_MSG = FAILURE_MSG + result
                        }
                    }    
                }  
            }
        }
    post {
        always {
            script {
                sh "${FAILURE_MSG}" // Hint: Use correct String Interpolation
                }
        }
    }
}

(类似的SO问题可以在here找到)

【讨论】:

    猜你喜欢
    • 2018-11-10
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 2022-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多