问题描述
我在从地图获取字符串列表后遇到 Cloudformation 问题。
"123456":
us-east-1:
#VPC1
VpcId: vpc-xxxx
VpcCidr: 10.78.160.0/20
SecurityGroups: sg-123
AvailabilityZones: us-east-1a,us-east-1b,us-east-1c
"123457":
us-east-1:
#VPC
VpcId: vpc-xxxx
VpcCidr: 10.78.160.0/20
SecurityGroups: sg-123,sg-124
AvailabilityZones: us-east-1a,us-east-1c
LaunchConfig:
Type: AWS::AutoScaling::LaunchConfiguration
Metadata:
AWS::CloudFormation::Init:
config:
Properties:
InstanceType:
Ref: InstanceType
SecurityGroups: !Join [ ",",[!FindInMap [!Ref "AWS::AccountId",!Ref "AWS::Region",SecurityGroups],!Ref EC2SG ]]
IamInstanceProfile:
通过这个问题解决
How do I use nested lists or append to a list in Cloudformation?
解决方法
让我们进行映射:
Mappings:
"111222333444":
us-east-1:
SecurityGroups:
- sg-abc
- sg-xyz
us-west-2:
SecurityGroups:
- sg-1234
- sg-3456
安全组可以称为
SecurityGroupIds:
"Fn::FindInMap":
[!Ref AWS::AccountId,!Ref AWS::Region,SecurityGroups]
在映射中定义为数组并传递完整数组,这样我们就可以避免分裂和连接。
完整模板,在 Lambda 上测试
AWSTemplateFormatVersion: "2010-09-09"
Description: "Test"
Mappings:
"111222333444":
us-east-1:
SecurityGroups:
- sg-abc
- sg-xyz
us-west-2:
SecurityGroups:
- sg-1234
- sg-3456
Resources:
TestLambda:
Type: "AWS::Lambda::Function"
Properties:
Handler: com.test.MainClass::handleRequest
Runtime: java8
FunctionName: "Test-Lambda"
Code:
S3Bucket: code-bucket
S3Key: !Sub "artifacts/test.jar"
Description: "Test Lambda"
MemorySize: 512
Timeout: 60
Role: !Ref my-role-arn
VpcConfig:
SecurityGroupIds:
"Fn::FindInMap":
[!Ref AWS::AccountId,SecurityGroups]
SubnetIds:
- subnet-1
- subnet-2