使用Groovy脚本从Jenkins中的工作区读取.json文件

c90pui9n  于 2022-11-01  发布在  Jenkins
关注(0)|答案(1)|浏览(451)

我想在工作区中的Prepare Artifacts阶段读取一个.json文件。
如何在staging groovy中读取工作区文件路径并运行代码?
下面的代码我用:

checkout scm: [
                        $class: 'GitSCM',
                        branches: [[name: "FETCH_HEAD"]],
                        extensions: [
                            [$class: 'RelativeTargetDirectory',
                                relativeTargetDir: repo2],
                            [$class: 'WipeWorkspace'],
                            [$class: 'CloneOption',
                                depth: 1,
                                noTags: true,
                                reference: '',
                                shallow: true,
                                honorRefspec: true],
                            [$class: 'CheckoutOption',
                                timeout: 30]],
                        gitTool: 'Default',
                        submoduleCfg: [],
                        userRemoteConfigs: [
                            [credentialsId: 'JENKINS_LOGIN',
                           ]
                        ]
                    ]
                    def releasePackages = readJSON file: "./BuildAutomation/Jenkins/Pipeline//files/release_package.json"
                    println releasePackages
                }
            }
        }

        stage('Prepare Variable') {
            steps {
                script{

                        for(file in releasePackages[buildMod]['India']) {
                            bat("xcopy ..\\CALReleaseOutput\\${file} ..\\${IndiaReleaseOutputFolder}\\${file} /I /E /Y")
                        }

for(file in releasePackages[buildMod]['Russia']) {
                                bat("xcopy ..\\CALReleaseOutput\\${file} ..\\${RussiaReleaseOutputFolder}\\${file} /I /E /Y")
                            }

                            zip archive: false, dir: "..\\${b2bReleaseOutputFolder}", glob: '', zipFile: "..\\CALReleaseOutput_${tagFoldername}_B2B.zip"
                        }
                    }
                }
            }

        }
    }
}

当我运行上面的一个时,我得到如下错误消息Console Output

vc9ivgsu

vc9ivgsu1#

如果要在阶段之间使用变量,则必须将其定义为全局变量。因此,请尝试在管道外部定义releasePackages。以下是一个示例。

def releasePackages

pipeline {
    agent any

    stages {
        stage('SetVariable') {
            steps {
                script {
                    releasePackages = readJSON file: "./BuildAutomation/Jenkins/Pipeline//files/release_package.json"
                    echo "$releasePackages"
                }
            }
        }
        stage('UseVariable') {
            steps {
                   echo "$releasePackages"           
            }
        }
    }
}

相关问题