Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify JSON-formatted string in Cloudformation?

I have the following resource on my CloudFormation template to create a rule to run a Lambda function, from the AWS documentation:

  "ScheduledRule": {
    "Type": "AWS::Events::Rule",
    "Properties": {
    "Description": "ScheduledRule",
    "ScheduleExpression": "rate(5 minutes)",
    "State": "ENABLED",
    "Targets": [{
      "Arn": { "Fn::GetAtt": ["myLambda", "Arn"] },
      "Id": "TargetFunctionV1"
    }]
    }
  }

I would like to specify the Input:

{
  "Arn" : String,
  "Id" : String,
  "Input" : String,
  "InputPath" : String
}

and Input is a JSON-formatted text string that is passed to the target. This value overrides the matched event.

I would like my JSON formatted text to be:

{
  "mykey1": "Some Value"
}

I do not know how to specify it in the Input, when I put:

  "ScheduledRule": {
    "Type": "AWS::Events::Rule",
    "Properties": {
    "Description": "ScheduledRule",
    "ScheduleExpression": "rate(5 minutes)",
    "State": "ENABLED",
    "Targets": [{
      "Arn": { "Fn::GetAtt": ["myLambda", "Arn"] },
      "Id": "TargetFunctionV1",
      "Input": { "mykey1": "Some Value" }
    }]
    }
  }

I will get error:

Value of property Input must be of type String

How should I specify it correctly?

like image 515
Steven Yong Avatar asked Aug 19 '16 14:08

Steven Yong


3 Answers

I would use YAML as it is easier and more readable:

Input:
  !Sub |
    {
        mykey1: "${myKey}"
    }
like image 74
Pau Avatar answered Sep 29 '22 09:09

Pau


Found out the answer myself:

"Input": "{ \"test\" : \"value11\", \"test2\" : \"value22\"}"

Hope it helps someone else.

Update:

You basically use the result of JSON.Stringify() to get the string into "Input" field. Use online JSON.Stringify() like https://onlinetexttools.com/json-stringify-text

like image 29
Steven Yong Avatar answered Sep 29 '22 08:09

Steven Yong


I wanted to expand on @Pau's answer. Basically if you use the | to say that the whole block below is to be treated as a raw string.

If you need to replace any variable in the JSON then you can use Sub, but if you don't have any variables, then you don't need Sub. An example would be:

Input:|
  {
    "jsonVar":"jsonVal",
    "jsonVar2" : "jsonVal2"
  }

You can later do JSON.parse(<input-variable>) to get the JSON object.

NOTE: Don't put commas at the end of the variables in JSON, if there is no next variable. Example :

Input:|
  {
    "jsonVar":"jsonVal",
    "jsonVar2" : "jsonVal2",
  }

This will cause JSON parsing errors.

like image 28
Mooncrater Avatar answered Sep 29 '22 09:09

Mooncrater