Jenkins管道-保存到文件构建作业属性

w41d8nur  于 2023-10-17  发布在  Jenkins
关注(0)|答案(1)|浏览(93)

请帮助我如何保存到文件构建作业属性尝试在下面的方式,我得到以下文本文件:[slave:org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper@7fb29d4c]

def jobsResult      = [:]

pipeline {
    agent { label 'Apps' }
    
    stages {
        stage('Exec Job') 
            steps {
                script {
                    echo "Stage name is : ${STAGE_NAME}"
                    try {
                        jobsResult.job_01 = build job: "job_01", propagate: true, wait: true
                        jobsResult.job_02 = build job: "job_02", propagate: true, wait: true
                    }
                    catch (e) {
                        echo "Slave job failed, marking build as UNSTABLE"
                        currentBuild.result = 'UNSTABLE'
                    }
                    
                    writeFile file: "jobsResults.txt", text: "${jobsResult}"
                }
            }
        }
        stage('Sleep') {
            steps {
                script {
                    echo "Stage name is : ${STAGE_NAME}"
                    try {
                        sleep 10
                    } catch (Exception e) {
                        echo "Sleep stage failed, but continuing..."
                    }
                }
            }
        }
    }
}
yzuktlbb

yzuktlbb1#

当您使用

writeFile file: "jobsResults.txt", text: "${jobsResult}"

jobsResult的字符串表示写入文件,即[slave:org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper@7fb29d4c]
您应该使用writeJSON,它会将map对象序列化为JSON并写入文件

writeJSON file: "jobsResults.json", json: jobsResult

由于writeJSON只适用于Map对象,您可能需要将对象转换为Map,以便您可以成功地将数据保存到文件中。
一个可能的解决方案是定义以下方法ref

def extractProperties(obj) {
    obj.getClass()
       .declaredFields
       .findAll { !it.synthetic }
       .collectEntries { field ->
           [field.name, obj."$field.name"]
       }
}

然后将下面的行从

jobsResult.job_01 = build job: "job_01", propagate: true, wait: true

def job_01 = build job: "job_01", propagate: true, wait: true
jobsResult.job_01 = extractProperties(job)

相关问题