使用CloudFormation的Fn::ForEach时遭遇重复项错误排查
问题原因及修复方案
你的报错是因为Fn::ForEach的输出结构不符合SecurityGroupIngress的要求。SecurityGroupIngress需要是数组类型,但当前写法会让循环生成的多个Ingress规则被合并成单个对象,导致重复的SourceSecurityGroupId键冲突。
修复后的完整代码
AWSTemplateFormatVersion: '2010-09-09' Transform: 'AWS::LanguageExtensions' Resources: MySqlIncomingSecurityGroups: Type: 'AWS::EC2::SecurityGroup' Properties: GroupDescription: Security for MySql RDS database SecurityGroupEgress: - CidrIp: 0.0.0.0/0 Description: Allow all outbound traffic by default IpProtocol: '-1' VpcId: vpc-123 SecurityGroupIngress: 'Fn::ForEach::Iterator': - CurrentSG - ["sg-1", "sg-2", "sg-3"] - - SourceSecurityGroupId: !Sub "${CurrentSG}" Description: Allow all MySQL inbound IpProtocol: tcp FromPort: 3306 ToPort: 3306
关键修改点
- 调整循环输出结构:在循环的第三个参数(规则模板)外层添加一个破折号
-,让每次迭代都生成一个独立的数组元素,最终SecurityGroupIngress会被转换为包含3条规则的数组,而非单个冲突对象。 - 规范变量插值:使用
!Sub函数解析CurrentSG变量(YAML直接写"${CurrentSG}"也可生效,但!Sub更符合CloudFormation最佳实践)。
内容的提问来源于stack exchange,提问作者jftuga
相关产品推荐
相关产品推荐

