Search code examples
jenkinsjenkins-plugins

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.


Solution

  • 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"
    }