首页 > 解决方案 > Jenkins 管道因文件读取错误替换错误而失败

问题描述

我正在编写一个脚本管道作为多分支管道的一部分,我需要在其中从 JSON 文件中读取键值对。当我运行管道时,我收到以下错误:/home/jenkins/workspace/dMyproject-QRMU74PK33RGCZRTDPVXCWOT55L2NNSXNPY2LJQ5R2UIIYSJR2RQ@tmp/durable-c4b5faa2/script.sh:替换错误

对我的代码进行了一些研究,我发现这一行特别导致了错误:

String fileContents = new File( ".env" ).text;

但我不知道,到底出了什么问题。我的 env 文件如下所示:

{
"key" :"value",
"key2" :"value2"
}
import groovy.json.JsonSlurper
import java.io.File 


node('google-cloud-node') {
   dockerfile {
      filename 'BuildDockerfile'
    }
    currentBuild.result = "SUCCESS"
    try {
        String dockerFileName = "BuildDockerfile"
        def customImage = docker.build("my-image:${env.BUILD_ID}","-f ${dockerFileName} .")

        customImage.inside('-u root') {
            stage('Checkout'){
                checkout scm
            }
            stage('Build'){
              notify("#test-ci-builds","Oh, time to  build something!")
                sh '''
                set +x
                whoami
                pwd
                npm install
                npm build
               '''
             }
             stage('Deploy') {
                        parseArgsFile()
                        withCredentials([file(credentialsId: "scanner-dev-ssh-service-account", variable: 'ID')]) {
                            sh '''
                              set +x
                              gcloud auth activate-service-account jenkins-test1@scanner-dev-212008.iam.gserviceaccount.com --key-file=$ID  --project=scanner-dev-212008
                              gcloud compute --project scanner-dev-212008 ssh --zone us-west2-a ubuntu@docker-slave --command "uname -a"
                            '''
                        }
             }
         }
    }
    catch (err) {
        notify("#test-ci-builds","Oh, crap!")
        currentBuild.result = "FAILURE"
            sh 'echo  ${env.BUILD_URL}'
        throw err
    }

}

def notify(channel,text) {
  slackSend (channel: "${channel}", message: "${text}", teamDomain: "distillery-tech", token: "0W6205gwiR1CEVOV4iMFiNQw")
}

def parseArgsFile(params=null){

    String fileContents = new File( ".env" ).text;
    def InputJSON = new JsonSlurper().parseText(inputFile.text)
    InputJSON.each{ println it }
}

标签: jenkinsgroovyjenkins-pipeline

解决方案


简短的回答

而不是使用new FileJsonSlurper简单地使用该readJSON步骤。

长答案

您的脚本中存在多个问题:

  1. 您不能File在管道中使用对象。事实上你可以,但这些文件总是会在 Jenkins 主服务器上被引用,并且需要禁用沙盒。您不能使用File对象从构建代理读取文件。相反,使用管道步骤readFile
  2. JsonSlurper不能在纯管道代码中使用,因为它没有实现Serializable接口。您需要将所有内容封装在@NonCPS方法中。但是,您不应该这样做,因为@NonCPS代码在重新启动后无法中止或继续,并且存在readJSONPipeline 实用程序步骤。

推荐阅读