Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to a json file in workspace using Jenkins

I've a jenkins job with few parameters setup and I've a JSON file in the workspace which has to be updated with the parameters that I pass through jenkins.

Example:

I have the following parameters which I'll take input from user who triggers the job:

  • Environment (Consider user selects "ENV2")
  • Filename (Consider user keeps 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 whatever the value is given by user before triggering a job has to be replaced in the job.json.

So when the user triggers the job, the job.json file should be:

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

Please note the environment value in the json which has to be updated.

I've tried https://wiki.jenkins-ci.org/display/JENKINS/Config+File+Provider+Plugin plugin. But I'm unable to find any help on parameterizing the values.

Kindly suggest on configuring this plugin or suggest any other plugin which can serve my purpose.

like image 316
Vimalraj Selvam Avatar asked Jul 20 '15 20:07

Vimalraj Selvam


2 Answers

Config File Provider Plugin doesn't allow you to pass parameters to configuration files. You can solve your problem with any scripting language. My favorite approach is using Groovy plugin. Hit a check-box "Execute system Groovy script" 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"
}
like image 62
Vitalii Elenhaupt Avatar answered Nov 09 '22 18:11

Vitalii Elenhaupt


With 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
like image 39
Ivan Ponomarev Avatar answered Nov 09 '22 17:11

Ivan Ponomarev