Cloudformation 安全组配置使用列表

kk.*_*kk. 5 amazon-web-services aws-cloudformation aws-security-group

我正在定义一个 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
Run Code Online (Sandbox Code Playgroud)

无论我用“ ”、“,”或“;”分隔它们,这都不允许创建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
Run Code Online (Sandbox Code Playgroud)

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

小智 1

AWS cloudformation 的自定义资源使您能够在模板中编写自定义预置逻辑,AWS CloudFormation 在您创建、更新(如果您更改了自定义资源)或删除堆栈时随时运行。

您可以使用AWS Lambda 支持的自定义资源。当您将 Lambda 函数与自定义资源关联时,每当创建、更新或删除自定义资源时都会调用该函数。AWS CloudFormation 调用 Lambda API 来调用该函数并将所有请求数据(例如请求类型和资源属性)传递给该函数。

Lambda 函数的强大功能和可定制性与 AWS CloudFormation 相结合,您可以以自定义方式更新安全组。

有一些开源项目可以帮助你快速编写