Reputation: 143
I'm a beginner with shell scripting and i have some issues while a jenkins job parametrized. I want to write all parameters of jenkins job pipeline build with parameters into a JSON file using ${params}
!
In my case i have 4 parameters(apis:multi-select,name:string,version:single-select and status:Boolean), there is the script Jenkinsfile
pipeline {
agent any
stages {
stage('Build') {
steps {
script{
sh "./test.sh ${params}"
}
}
}
}
}
Content of test.sh
#!/bin/bash
echo $@ > file.json
The output in jenkins
+ ./test.sh [apis:dev,qa,prod, name:CC, version:g3, status:true]
Result in file.json
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
My question is how format the output to obtain a clean result in file.json ? please i need help.
Upvotes: 2
Views: 4394
Reputation: 129
The Jenkins pipeline script you posted is almost correct for writing parameters into a JSON file. But it has a small issue - it tries to serialize the params object, which is a special Jenkins object, directly to a JSON file.
This object contains more data than just the parameters and its metadata can't be serialized directly to a JSON. So, to solve this, you need to map each parameter to a new map and then serialize that map into JSON. Below is a corrected version of your script:
import groovy.json.JsonOutput
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
def paramsMap = [:]
paramsMap['apis'] = params['apis']
paramsMap['name'] = params['name']
paramsMap['version'] = params['version']
paramsMap['status'] = params['status']
writeFile file: 'params.json', text: JsonOutput.toJson(paramsMap)
}
}
}
}
}
This script will only serialize the parameters you're interested in, instead of trying to serialize the entire params object. Note that in Jenkins, the params object includes the parameters from the current build and any default parameters defined in the job configuration.
This approach can be easily adjusted to add or remove parameters from the output JSON file. Just add or remove lines in the paramsMap creation part of the script.
Upvotes: 0
Reputation: 176
Add this to the top of your script:
import groovy.json.JsonOutput
Then use this line instead of sh "./test.sh ${params}"
:
writeFile file: 'params.json', text: JsonOutput.toJson(params)
This uses a Groovy library and a native Jenkins method for writing files, which means you don't need to use the sh
method.
Upvotes: 4