jenkins - 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 }
}
解决方案
简短的回答
而不是使用new File
并JsonSlurper
简单地使用该readJSON
步骤。
长答案
您的脚本中存在多个问题:
- 您不能
File
在管道中使用对象。事实上你可以,但这些文件总是会在 Jenkins 主服务器上被引用,并且需要禁用沙盒。您不能使用File
对象从构建代理读取文件。相反,使用管道步骤readFile
JsonSlurper
不能在纯管道代码中使用,因为它没有实现Serializable
接口。您需要将所有内容封装在@NonCPS
方法中。但是,您不应该这样做,因为@NonCPS
代码在重新启动后无法中止或继续,并且存在readJSON
Pipeline 实用程序步骤。
推荐阅读
- sql - 用零向左填充文本字段
- python - 为什么我会收到来自错误 API 端点的响应?
- angular - 将组件范围传递给商店服务是不好的做法 - Angular
- c++ - g++ 5.5没有链接共享库
- java - REST API 帖子给出 html 响应
- windows - COM 端口需要多长时间才能在 Windows 上可用?
- c# - 将组件存储在静态类中可行吗?
- angular - NGRX Redux 存储——即使智能感知自动完成并且模型中的所有内容都匹配,仅选择状态的一部分也会返回“未定义”
- android - ELM327 蓝牙通讯问题
- oracle-cloud-infrastructure - 从 Libreswan 路由模式到 DRG 的 IPSEC 隧道