Khalid Waseem
Khalid Waseem

Reputation: 119

How to stringify the JSON file content in Jenkins groovy file

I have to put the Json file into the AWS SSM parameter through the Cloudformation. I have written the CFT to create the SSM parameter but I am facing the challenges in passing the Parameter value which would be the JSON file content.

Parameters:
  Environment:
    Description: 'Deployment Environment'
    Type: String
    Default: dev
  SSMParameterName:
    Description: 'SSM Parameter Name'
    Type: String
    Default: testswapeligibility
  JsonFormatToPutInSSM:
    Description: 'Provide the text in JSON format to put on SSM parameter'
    Type: String
    Default: '{"This_is_sample":"Sample1,Sample2","Name":"some thing here","anything_else":""}'

Resources:  
  JsonFormatToPutInSSM:
    Type: AWS::SSM::Parameter
    Properties:
      Description: 'SSM Parameter to hold LogGroup names and details for which Subscription filter needs to be created'
      Name: !Sub '/app/rds/${SSMParameterName}-${Environment}'
      Type: String
      Value:  !Sub '${JsonFormatToPutInSSM}'

Now I have Jenkins job to deploy this CFT. In that Jenkins job, I am getting the JSON file from the Git and reading the JSON file and want to pass that JSON file content as a value to "SSMParameterName" parameter.

In cloud formation it does not support the JSON file directly and need to Reserved JSON characters, such as backspaces, form feeds, newlines, carriage returns, tabs, double quotes and backslashes are escaped with an extra backslash. I want to perform this in groovy itself and pass the formated JSON file content as json string to Cloudformation parameter value. How to convert: e.g

{"This_is_sample":"Sample1,Sample2","Name":"some thing here","anything_else":""}

Into

{\"This_is_sample\":\"Sample1,Sample2\",\"Name\":\"some thing here\",\"anything_else\":\"\"}

In Jenkins file itself and pass it to Cloudformation command as parameter value.

Upvotes: 0

Views: 33

Answers (1)

chubbsondubs
chubbsondubs

Reputation: 38842

So I'm thinking you're doing something like this:

stage('SSMConfig') {
   steps {
      def jsonParams = readJson file: "path/to/json/parameters"

      script {
         def escapedJson = JsonOutput.toJson( JsonOutput.toJson( jsonParams ) )
      }
   }   
}

By running JsonOutput.toJson twice the 2nd execution will escape everything you had in your JSON string. Also by parsing JSON from the file from GIT you remove all whitespace and other things that can trip you up when putting the output into a parameter so there won't be any \n or \t in the output that could trip you up.

Upvotes: 0

Related Questions