Reputation: 3
I am writing a scripted pipeline as part of multibranch pipeline in which I need to read a key-value pairs from a JSON file. When I run the pipeline I am getting the following error: /home/jenkins/workspace/dMyproject-QRMU74PK33RGCZRTDPVXCWOT55L2NNSXNPY2LJQ5R2UIIYSJR2RQ@tmp/durable-c4b5faa2/script.sh: Bad substitution
Doing a little research of my code I found out that particulary this line is causing the error:
String fileContents = new File( ".env" ).text;
But I cant find out, what's exactly wrong. My env file looks like this:
{
"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 [email protected] --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 }
}
Upvotes: 0
Views: 1777
Reputation: 5149
Instead of using new File
and JsonSlurper
simply use the readJSON
step.
There‘s more than one issue in your script:
File
objects in the Pipeline. In fact you could but those files would always get referenced on the Jenkins master and would require to have the sandboxing disabled. You cannot read files from a build agent using a File
object. Instead, use the Pipeline step readFile
JsonSlurper
cannot be used in plain Pipeline code as it doesn’t implement the Serializable
interface. You would need to encapsulate everything inside a @NonCPS
method. However you should not do that either as @NonCPS
code cannot be aborted or continued after a restart and there’s the readJSON
Pipeline utility step.Upvotes: 1