[英]How to specify JSON-formatted string in Cloudformation?
我的 CloudFormation 模板上有以下資源,用於從 AWS 文檔創建運行 Lambda 函數的規則:
"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
}
Input 是傳遞給目標的 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" }
}]
}
}
我會得到錯誤:
Value of property Input must be of type String
我應該如何正確指定它?
自己找到了答案:
"Input": "{ \\"test\\" : \\"value11\\", \\"test2\\" : \\"value22\\"}"
希望它可以幫助別人。
更新:
您基本上使用 JSON.Stringify() 的結果將字符串放入“輸入”字段。 使用在線 JSON.Stringify() 像https://onlinetexttools.com/json-stringify-text
我會使用 YAML,因為它更容易且更易讀:
Input:
!Sub |
{
mykey1: "${myKey}"
}
我想擴展@Pau 的回答。 基本上,如果您使用|
說下面的整個塊將被視為原始字符串。
如果您需要替換 JSON 中的任何變量,則可以使用Sub
,但如果您沒有任何變量,則不需要Sub
。 一個例子是:
Input:|
{
"jsonVar":"jsonVal",
"jsonVar2" : "jsonVal2"
}
您可以稍后執行JSON.parse(<input-variable>)
來獲取 JSON 對象。
注意:如果沒有下一個變量,請不要在 JSON 中的變量末尾添加逗號。 例子 :
Input:|
{
"jsonVar":"jsonVal",
"jsonVar2" : "jsonVal2",
}
這將導致 JSON 解析錯誤。
這應該工作:
"Input": JSON.stringify({ mykey1: "Some Value" })
如果您在 yaml 中編寫 CloudFormation 腳本並且發現很難使用 JSON 字符串(例如策略文檔),最簡單的方法是使用在線轉換器將 JSON 轉換為 yaml
ApiGatewayRestApi:
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\"]}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.