首页 > 解决方案 > AWS CloudFormation - AWS::ElasticLoadBalancingV2::LoadBalancer - SecurityGroups

问题描述

CFN 模板中是否有可能根据参数向 ALB 添加一些特定的安全组?

我有两个安全组添加到 ALB 的情况:

ALB
  Type: AWS::ElasticLoadBalancingV2::LoadBalancer
  Properties:
    ...
    SecurityGroups:
      - !Ref 'SecurityGroup1'
      - !Ref 'SecurityGroup2'

现在SecurityGroup3只有当某个参数具有特定值时,我才想最终添加一个。假设如果参数add_sg3等于yes,则将第三个 SG 添加到 ALB。我总是"!If在类似的情况下使用,但有超过 2 个 SG。任何的建议都受欢迎。谢谢!

标签: amazon-cloudformation

解决方案


您可以使用ConditionAWS::NoValue伪参数来实现。下面是一个完整的例子:

Parameters:
    Environment:
        Type: String
        Default: dev
        AllowedValues: ["dev", "prod"]
    VpcId:
        Type: 'AWS::EC2::VPC::Id'
    Subnet1:
        Type: 'AWS::EC2::Subnet::Id'
    Subnet2:
        Type: 'AWS::EC2::Subnet::Id'

Conditions:
    MyTest: !Equals ["dev", !Ref Environment]

Resources:
    ALB:
        Type: 'AWS::ElasticLoadBalancingV2::LoadBalancer'
        Properties:
            SecurityGroups:
            - !Ref SecurityGroup1
            - !If [ MyTest, !Ref SecurityGroup2, !Ref 'AWS::NoValue' ]
            Subnets:
            - !Ref Subnet1
            - !Ref Subnet2

    SecurityGroup1:
        Type: 'AWS::EC2::SecurityGroup'
        Properties:
            GroupDescription: 'Group 1'
            VpcId: !Ref VpcId

    SecurityGroup2:
        Type: 'AWS::EC2::SecurityGroup'
        Properties:
            GroupDescription: 'Group 2'
            VpcId: !Ref VpcId

推荐阅读