我的 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"
}]
}
}
我想指定输入:
{
"Arn" : String,
"Id" : String,
"Input" : String,
"InputPath" : String
}
输入是传递给目标的 JSON 格式的文本字符串。该值会覆盖匹配的事件。
我希望我的 JSON 格式文本为:
{
"mykey1": "Some Value"
}
当我输入时,我不知道如何在输入中指定它:
"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" }
}]
}
}
我会收到错误:
属性输入的值必须是 String 类型
我该如何正确指定?
我会使用 YAML,因为它更容易且更具可读性:
Input:
!Sub |
{
mykey1: "${myKey}"
}
我自己找到了答案:
"Input": "{ \"test\" : \"value11\", \"test2\" : \"value22\"}"
希望对其他人有帮助。
更新:
您基本上使用 JSON.Stringify() 的结果将字符串输入“输入”字段。使用在线 JSON.Stringify() 如 https://onlinetexttools.com/json-stringify-text
我想扩展@Pau 的答案。基本上,如果您使用
|
表示下面的整个块将被视为原始字符串。
如果您需要替换 JSON 中的任何变量,那么您可以使用
Sub
,但如果您没有任何变量,则不需要 Sub
。一个例子是:
Input:|
{
"jsonVar":"jsonVal",
"jsonVar2" : "jsonVal2"
}
您可以稍后执行
JSON.parse(<input-variable>)
来获取 JSON 对象。
注意:如果没有下一个变量,请勿在 JSON 中的变量末尾添加逗号。示例:
Input:|
{
"jsonVar":"jsonVal",
"jsonVar2" : "jsonVal2",
}
这会导致 JSON 解析错误。
如果您在 yaml 中编写 CloudFormation 脚本,并且发现很难使用 JSON 字符串(例如策略文档),最简单的方法是使用 在线转换器
将 JSON 转换为 yamlApiGatewayRestApi:
Type: AWS::ApiGateway::RestApi
Properties:
Description: API Gateway for some API
EndpointConfiguration:
Types:
- PRIVATE
Name: MyAPIGateway
Policy: <Policy Doc >
假设政策文档如下。
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "arn:aws:execute-api:ap-southeast-2:something/*",
"Condition": {
"ForAnyValue:StringEquals": {
"aws:sourceVpce": "vpce-abcd"
}
}
}
]
}
使用转换器,您可以将 JSON 转换为相同的 yaml 并按如下方式使用。
ApiGatewayRestApi:
Type: AWS::ApiGateway::RestApi
Properties:
Description: API Gateway for some API
EndpointConfiguration:
Types:
- PRIVATE
Name: MyAPIGateway
Policy:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal: "*"
Action: execute-api:Invoke
Resource: arn:aws:execute-api:ap-southeast-2:something/*
Condition:
ForAnyValue:StringEquals:
aws:sourceVpce: vpce-abcd
这是我的“输入”行的类似 YAML 代码。我花了一整天的时间来弄清楚语法,所以我希望这可以帮助将来的人。
Input: "{\"action\":[\"configure\"],\"mode\":[\"ec2\"],\"optionalConfigurationSource\":[\"ssm\"],\"optionalConfigurationLocation\":[\"AmazonCloudWatch-Baseline-Windows\"],\"optionalRestart\":[\"yes\"]}"