具有多个 CIDR IP 的云形成安全组的 YAML CF 模板

YAML CF template for Cloud formation security group with multiple CIDR IPs

我正在 YAML 中为安全组创建 cloudformation 模板,目的如下。

如果我在参数 (IP) 中输入 3 个 CIDR IP(59.188.255.128/26,34.224.81.192/26,35.223.13.224/27),则应该使用入口 3 个 CIDR IP 创建安全组。 如果我在参数 (IPs) 中输入 2 CIDR IPs(59.188.255.128/26,34.224.81.192/26),则应该使用这些入口 2 CIDR IPs 创建安全组。 如果我在参数 (IPs) 中输入 1 CIDR IP(59.188.255.128/26),则应该使用该入口 1 CIDR IP 创建安全组。

我在 Cloudformation 设计器中验证我的模板时遇到错误。

Template contains errors.: Template format error: YAML not well-formed. (line 17, column 28)

下面的模板能达到目的吗? 我也无法检测到错误。有人可以帮我解决这个问题吗?

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 three CIDR IPs
    Type: CommaDelimitedList
Conditions:
  IsIPthereA: !Not [!Equals["",!Select [ 0, !Ref IPs ] ]]
  IsIPthereB: !Not [!Equals["",!Select [ 1, !Ref IPs ] ]]
  IsIPthereC: !Not [!Equals["",!Select [ 2, !Ref IPs ] ]]
Resources:
  MYSG:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: !Ref Description
      VpcId: !Ref VPC
      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

更新: 无效错误得到修复。现在,使用 3 个 CIDR IP 作为参数创建堆栈没有问题。但是在使用 2 个 CIDR IP 创建堆栈作为参数输入 (54.183.255.128/26,34.223.80.192/26) 时,我收到“模板错误:Fn::Select 不能 select 索引 2 处不存在的值”。有人可以帮助修复此错误吗?

校验错误是因为!Equals.

后没有space

即使您修复了 space 问题,当 IPs 数组的长度不是 3 时它也会失败,因为 !Select 函数无法 select 来自不包含长度的索引不存在。

为了使其正常工作,请使用空字符串加入您的列表,然后进行验证。

Conditions:
  IsIPthereA: 
    Fn::Not: 
      - Fn::Equals:
        - Fn::Select:
          - 0
          - Fn::Split:
            - ","
            - Fn::Sub:
              - "${IP},,,"
              - IP: !Join [',', !Ref IPs] 
        - ""
  IsIPthereB: 
    Fn::Not: 
      - Fn::Equals:
        - Fn::Select:
          - 1
          - Fn::Split:
            - ","
            - Fn::Sub:
              - "${IP},,,"
              - IP: !Join [',', !Ref IPs] 
        - ""
  IsIPthereC: 
    Fn::Not: 
      - Fn::Equals:
        - Fn::Select:
          - 2
          - Fn::Split:
            - ","
            - Fn::Sub:
              - "${IP},,,"
              - IP: !Join [',', !Ref IPs] 
        - ""