CloudFormation安全组YAML模板动态CIDR配置报错排查咨询
CloudFormation安全组模板修复方案
错误原因
- 初始YAML格式错误:内置函数标签(如
!Equals)和后续参数列表之间缺少空格,导致YAML解析失败。 - Fn::Select索引越界错误:CloudFormation在模板评估阶段会先执行所有
!Select逻辑,再判断条件是否成立。当输入的CIDR数量不足3个时,直接访问索引1、2会因为列表长度不够直接报错,不会等到条件判断环节跳过对应逻辑。
修复后的完整模板
AWSTemplateFormatVersion: 2010-09-09 Description: Security Group for CIDR IPs Parameters: VPC: Type: AWS::EC2::VPC::Id Description: VPC where the Security Group will belong Name: Type: String Description: Name Tag of the Security Group Description: Type: String Description: Description Tag of the Security Group IPs: Description: Comma-delimited list of 1-3 CIDR IPs Type: CommaDelimitedList Conditions: # 先将输入的CIDR列表补全到至少3个元素,不足位补空字符串,避免Select越界 IsIPthereA: !Not [!Equals ["", !Select [0, !Split [",", !Join [",", [!Join [",", !Ref IPs], "", ""]]]]] IsIPthereB: !Not [!Equals ["", !Select [1, !Split [",", !Join [",", [!Join [",", !Ref IPs], "", ""]]]]] IsIPthereC: !Not [!Equals ["", !Select [2, !Split [",", !Join [",", [!Join [",", !Ref IPs], "", ""]]]]] Resources: MYSG: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: !Ref Description VpcId: !Ref VPC Tags: - Key: Name Value: !Ref Name SecurityGroupIngress: - IpProtocol: tcp CidrIp: !If [IsIPthereA, !Select [0, !Ref IPs], !Ref AWS::NoValue] FromPort: 443 ToPort: 443 - IpProtocol: tcp CidrIp: !If [IsIPthereB, !Select [1, !Ref IPs], !Ref AWS::NoValue] FromPort: 443 ToPort: 443 - IpProtocol: tcp CidrIp: !If [IsIPthereC, !Select [2, !Ref IPs], !Ref AWS::NoValue] FromPort: 443 ToPort: 443 Outputs: SecurityGroupID: Description: Security Group ID Value: !Ref MYSG
修复说明
- 修正了YAML语法:所有内置函数和参数列表之间补充了空格,解决初始的YAML格式校验错误。
- 解决索引越界问题:条件判断中先将输入的CIDR列表拼接两个空字符串后再拆分,保证拆分后的列表长度固定为3,不足位用空字符串填充,此时访问索引0、1、2不会触发越界错误。
- 兼容1-3个CIDR输入:对应位置的CIDR为空时,
!If逻辑会返回AWS::NoValue自动跳过对应入站规则,实现动态适配输入数量的需求。 - 补充了缺失的Name标签设置,符合参数定义的预期功能。
内容的提问来源于stack exchange,提问作者Gnay
相关产品推荐
相关产品推荐

