Writing to json file in the workspace using Jenkins

I have work with jenkins with setting several parameters, and I have a JSON file in the workspace that needs to be updated with the parameters that I pass through jenkins.

Example:

I have the following parameters that I will enter from the user who runs the task:

  • Wednesday (think user selects "ENV2")
  • File name (if the user saves the default value)

I have a json file in my workspace under run / job.json with the following contents:

{ environment: "ENV1", filename: "abc.txt" } 

Now, no matter what value is set by the user before starting the job, you need to replace it in job.json.

Therefore, when the user starts the job, the job.json file should be:

 { environment: "ENV2", filename: "abc.txt" } 

Notice the json environment value that needs to be updated.

I tried the https://wiki.jenkins-ci.org/display/JENKINS/Config+File+Provider+Plugin plugin. But I can not find help in parameterizing the values.

Please offer to configure this plugin or to offer any other plugin that may serve my purpose.

+6
source share
3 answers

The configuration file provider plugin does not allow the transfer of parameters to configuration files. You can solve your problem in any scripting language. My favorite approach is using the Groovy plugin . Check the "Run Groovy script system" box and paste the following script:

 import groovy.json.* // read build parameters env = build.getEnvironment(listener) environment = env.get('environment') filename = env.get('filename') // prepare json def builder = new JsonBuilder() builder environment: environment, filename: filename json = builder.toPrettyString() // print to console and write to a file println json new File(build.workspace.toString() + "\\job.json").write(json) 

Output Sample:

 { "environment": "ENV2", "filename": "abc.txt" } 
+8
source

I will keep it simple. A Windows batch file or shell script (depending on the OS) that will read the environment values ​​and open the JSON file and make changes.

0
source

With the Pipeline Utility Steps plugin, this is very easy to achieve.

  jsonfile = readJSON file: 'path/to/your.json' jsonfile['environment'] = 'ENV2' writeJSON file: 'path/to/your.json', json: jsonfile 
0
source

All Articles