从脚本返回的值未分配给在jenkins声明式管道阶段中声明的变量

时间:2019-11-21 10:07:09

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

我正在为自动化测试添加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:无此类属性:class:groovy.lang.Binding的failure_msg'

有人可以帮我吗?

编辑:

  

即使我固定了字符串插值,我也得到了相同的结果   错误。那是因为詹金斯不允许在内部使用'sh'   泊坞窗容器。 jenkins issue board

中有一个打开的错误通知单

1 个答案:

答案 0 :(得分: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
                }
        }
    }
}

(可以找到类似的类似问题here

相关问题