不确定这里或 SO 是否是询问此问题的更好地方...
我正在尝试拆分我们的 CloudFormation 模板,以使它们更易于使用且更小。
我遇到了一个问题,我希望使用基本上是空的“基本”安全组模板,然后引用该模板以及我需要创建的每个安全组的参数。
我的问题在于填写“SecurityGroupIngress/Egress”部分,因为这些部分包含 json 数组,据我所知,您只能通过参数传递字符串或数字。
这是一个例子;
父堆栈:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "CloudFormation template to create all Security Groups",
"Resources": {
"CommonSecurityGroupStack" : {
"Type" : "AWS::CloudFormation::Stack",
"DependsOn": [
],
"Properties" : {
"TemplateURL" : "https://s3.template.url/template.name",
"TimeoutInMinutes" : "60",
"Parameters": {
"VPC" : { "Ref": "VPC" },
"VpcCidrRange": { "Ref": "VpcCidrRange" },
"SecurityGroupIngress": { "Something here" },
"SecurityGroupName": "CommonSecurityGroup"
}
}
}
}
}
嵌套堆栈:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "CloudFormation template to create a security group",
"Parameters": {
"VPC": {
"Description": "Name of the VPC",
"Type": "String"
},
"GroupDescription": {
"Description": "Description of Security Group",
"Type": "String"
},
"SecurityGroupIngress" : {
"Description": "List of rules for the Security Group Ingress"
},
"VpcCidrRange": {
"Description": "CIDR IP range",
"Type": "String",
"MinLength": "9",
"MaxLength": "18",
"Default": "0.0.0.0/0",
"AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
"ConstraintDescription": "must be a valid CIDR range of the form x.x.x.x/x."
},
"SecurityGroupName": {
"Description": "Name of the Security Group",
"Type": "String"
}
},
"Resources": {
"SecurityGroup": {
"DependsOn": [],
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupDescription": { "Ref": "GroupDescription" },
"VpcId": {
"Ref": "VPC"
},
"SecurityGroupIngress": {"Ref" : "SecurityGroupIngress"},
"Tags": [
{
"Key": "Name",
"Value": { "Ref": "SecurityGroupName" }
}
]
}
}
}
}
我需要一种将某些内容传递给以下等价物的方法,将其作为参数传入堆栈以填充属性SecurityGroupIngress
。
[
{
"IpProtocol": "tcp",
"FromPort": "22",
"ToPort": "22",
"CidrIp": {
"Ref": "VpcCidrRange"
}
},
{
"IpProtocol": "tcp",
"FromPort": "443",
"ToPort": "443",
"CidrIp": {
"Ref": "VpcCidrRange"
}
}
]
答案1
不幸的是,CloudFormation 并不那么复杂。可用作参数的数据类型受到限制:
- 字符串
- 以逗号分隔的字符串列表
- 各种 AWS 资源类型,其中都不是入口规则
请尝试以下操作:
- 添加参数以包含/排除各种入口规则,
- 将入口规则作为资源移入嵌套堆栈
AWS::EC2::SecurityGroupIngress
,然后 - 根据您的参数使用条件来包含/排除各种入口规则
参考: