首页 > 解决方案 > Cloudformation 安全组配置使用列表

问题描述

我正在定义一个 cloudformation 堆栈,其中安全组应允许来自指定 IP 地址的入口流量。我已将这些 IP 地址定义为映射,当我们在我们的平台上加入新客户时,它们将在未来增长。我当前的 cloudformation 堆栈看起来像

AWSTemplateFormatVersion: '2010-09-09'  
Description: Security group.

Parameters:
  VPCStackName:
    Type: String
    Description: The name of VPC stack

Mappings:
  # Security group configuration for different environments
  SecurityGroupConfiguration:
    PROD: 
      IPAddress: "149.250.241.202/32 149.250.241.202/32"
    NON-PROD: 
      IPAddress: "149.250.241.202/32, 149.250.241.204/32, 149.250.241.205/32"

Resources:

  # Add security groups and their ingress
  PublicSubnetSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Test security group
      VpcId: 
        Fn::ImportValue:
          !Sub "${VPCStackName}-vpcid"
      SecurityGroupIngress:
        - CidrIp: !FindInMap ['SecurityGroupConfiguration', 'PROD', 'IPAddress']
          IpProtocol: -1

无论我用''、'、'或';'分隔它们,这都不允许创建SG。

我想尝试的第二种方法是将这些映射定义为一个列表,并根据配置的元素数量动态迭代它们。因为PRODNON-PROD列表将有不同数量的 IP 地址,所以我将无法定义索引。例如,生产将有 4 个 IP 地址,而非生产可能只有 2 个 IP 地址。如果我为 !Select 定义索引,相同的 CFN 模板将不适用于两种环境。

AWSTemplateFormatVersion: '2010-09-09'  
Description: Security group.

Parameters:
  VPCStackName:
    Type: String
    Description: The name of VPC stack

Mappings:
  # Security group configuration for different environments

  SecurityGroupConfiguration:
  PROD: 
    IPAddress: 
      - 149.250.241.202/32
      - 149.250.241.203/32
  NON-PROD: 
    IPAddress: 
      - 149.250.241.202/32
      - 149.250.241.204/32
      - 149.250.241.205/32

Resources:

  # Add security groups and their ingress
  PublicSubnetSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Test security group
      VpcId: 
        Fn::ImportValue:
          !Sub "${VPCStackName}-vpcid"
      SecurityGroupIngress:
        - CidrIp: for (i in SecurityGroupConfiguration)
            <Dynamically iterate over list to produce all the ip addresses>
            !Select [i, !FindInMap ['SecurityGroupConfiguration', 'PROD', 'IPAddress']]
          IpProtocol: -1

有没有办法解决这个问题?

标签: amazon-web-servicesamazon-cloudformationaws-security-group

解决方案


简短回答:前缀列表
完全避免您的问题的一个可能解决方案是创建一个包含所有 IP 的前缀列表(并且可以在以后修改),而不是在您的 SG 中引用该前缀列表。对您的前缀列表的未来更新会立即生效,而不会对您的实时 SG 进行任何修改。
有关详细信息,请参阅前缀列表

注意:如果您为大量 IP 设置此设置,请记住您的 VPC 限制(请参阅Amazon VPC 配额


推荐阅读