You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CloudFormation安全组YAML模板动态CIDR配置报错排查咨询

CloudFormation安全组模板修复方案

错误原因

  1. 初始YAML格式错误:内置函数标签(如!Equals)和后续参数列表之间缺少空格,导致YAML解析失败。
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 21:24:04