在 Jenkins 管道中,如何在电子邮件正文中显示 Groovy 映射的内容?

问题描述 投票:0回答:1

我有一个执行并行阶段的 Jenkins 声明式管道。每个阶段的退出代码分配给 Groovy map results 并打印到日志控制台:

def p = [:]         // map for parallel stages
def results = [:]   // map of exit code for each stage

pipeline {

    stages {
        stage('run') {
            steps {
                script {
                    for (file in files_list) {
                        p[file] = {
                            node(myagent) {
                                results[file] = sh returnStatus: true, script:'./myApp $file'
                            }
                        }
                    }

                    parallel p

                    // Print the results
                    for (def key in results.keySet()) {
                        println "file = ${key}, exit code = ${results[key]}"
                    }
                }
            }
        }  
    }

    post {
        success {
            script { emailext (subject: "${env.JOB_NAME}: Build #${env.BUILD_NUMBER} - Successful!",
                                body: '${DEFAULT_CONTENT}',
                                recipientProviders: [buildUser()])
            }
        }
    }
}

如何将地图的打印输出包含在成功后期发送的通知电子邮件的正文中?

jenkins groovy jenkins-pipeline jenkins-groovy
1个回答
0
投票

并行执行后,您可以迭代结果,将它们转换为全局保存的字符串,最后在发送邮件时将结果字符串与消息内容连接在一起。
比如:

       
results = ["Execution Results:"]  // List of all the accumulated results

pipeline {
    stages {
        stage('run') {
            steps {
                script {
                    def outputs = [:]
                    parallel files_list.collectEntries { file ->
                        ["${file}": {
                            node(myagent) {
                                outputs[file] = sh returnStatus: true, script:'./myApp $file'
                            }
                        }]
                    }

                    // Print and accumulate the results
                    outputs.each { file, exitCode ->
                        def line = "file = ${file}, exit code = ${exitCode}"
                        println(line) 
                        results.add(line)
                    }
                }
            }
        }  
    }

    post {
        success {
            emailext subject: "${env.JOB_NAME}: Build #${env.BUILD_NUMBER} - Successful!",
                     body: '${DEFAULT_CONTENT}' + results.join('\n'),  // Join all results item with a new line
                     recipientProviders: [buildUser()])
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.