如何在Cloudformation中指定JSON格式的字符串?

Ste*_*ong 11 json aws-cloudformation

我在CloudFormation模板上有以下资源来创建运行Lambda函数的规则,来自AWS文档:

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

我想指定输入:

{
  "Arn" : String,
  "Id" : String,
  "Input" : String,
  "InputPath" : String
}
Run Code Online (Sandbox Code Playgroud)

和Input是传递给目标的JSON格式的文本字符串.此值将覆盖匹配的事件.

我希望我的JSON格式文本是:

{
  "mykey1": "Some Value"
}
Run Code Online (Sandbox Code Playgroud)

当我放入时,我不知道如何在输入中指定它:

  "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" }
    }]
    }
  }
Run Code Online (Sandbox Code Playgroud)

我会得到错误:

Value of property Input must be of type String
Run Code Online (Sandbox Code Playgroud)

我该如何正确指定?

Ste*_*ong 8

自己找出答案:

“输入”:“ {\” test \“:\” value11 \“,\” test2 \“:\” value22 \“}”

希望它可以帮助别人。


Pau*_*Pau 5

我会使用YAML,因为它更容易阅读,也更具可读性:

Input:
  !Sub |
    {
        mykey1: "${myKey}"
    }
Run Code Online (Sandbox Code Playgroud)

  • 是的,它有效。您只需要使用YAML而不是JSON。 (3认同)

Moo*_*ter 5

我想扩展@Pau 的回答。基本上,如果您使用 the|来表示下面的整个块将被视为原始字符串。

如果您需要替换 JSON 中的任何变量,则可以使用Sub,但如果您没有任何变量,则不需要Sub. 一个例子是:

Input:|
  {
    "jsonVar":"jsonVal",
    "jsonVar2" : "jsonVal2"
  }
Run Code Online (Sandbox Code Playgroud)

您可以稍后JSON.parse(<input-variable>)获取 JSON 对象。

注意:如果没有下一个变量,请不要在 JSON 中的变量末尾添加逗号。例子 :

Input:|
  {
    "jsonVar":"jsonVal",
    "jsonVar2" : "jsonVal2",
  }
Run Code Online (Sandbox Code Playgroud)

这将导致 JSON 解析错误。