CloudFormation:有条件的 AutoScalingGroup 通知

CloudFormation: conditional AutoScalingGroup notifications

我想使用 SNS 接收 AutoScaling 事件通知,但仅限于我的 PROD 环境。如何配置我的 CloudFormation 模板来执行此操作?

是不是应该这样:

Parameters:
  Environment:
    Description: Environment of the application
    Type: String
    Default: dev
    AllowedValues:
      - dev
      - prod

Conditions:
  IsDev: !Equals [ !Ref Environment, dev]
  IsProd: !Equals [ !Ref Environment, prod]

Resources:
  mySNSTopic:
    Type: AWS::SNS::Topic
    Properties: 
      Subscription: 
        - Endpoint: "my@email.com"
          Protocol: "email"

  myProdAutoScalingGroupWithNotifications:
    Type: AWS::AutoScaling::AutoScalingGroup
    Condition: IsProd
    Properties:
      NotificationConfigurations:
        - NotificationTypes: 
            - "autoscaling:EC2_INSTANCE_LAUNCH_ERROR"
            - "autoscaling:EC2_INSTANCE_TERMINATE"
            - "autoscaling:EC2_INSTANCE_TERMINATE_ERROR"
          TopicARN: !Ref "mySNSTopic"

  myDevAutoScalingGroupWithoutNotifications:
    Type: AWS::AutoScaling::AutoScalingGroup
    Condition: IsDev
    Properties:

或者 CloudFormation 是否也支持以下内容:

Parameters:
  Environment:
    Description: Environment of the application
    Type: String
    Default: dev
    AllowedValues:
      - dev
      - prod

Conditions:
  IsProd: !Equals [ !Ref Environment, prod]

Resources:
  mySNSTopic:
    Type: AWS::SNS::Topic
    Properties: 
      Subscription: 
        - Endpoint: "my@email.com"
          Protocol: "email"

  myAutoScalingGroup:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      NotificationConfigurations:
        - Condition: IsProd
          NotificationTypes: 
            - "autoscaling:EC2_INSTANCE_LAUNCH_ERROR"
            - "autoscaling:EC2_INSTANCE_TERMINATE"
            - "autoscaling:EC2_INSTANCE_TERMINATE_ERROR"
          TopicARN: !Ref "mySNSTopic"

使用Fn::If函数应该是双倍的:

  NotificationConfigurations:
    - !If 
        - IsProd
        - NotificationTypes: 
            - "autoscaling:EC2_INSTANCE_LAUNCH_ERROR"
            - "autoscaling:EC2_INSTANCE_TERMINATE"
            - "autoscaling:EC2_INSTANCE_TERMINATE_ERROR"
          TopicARN: !Ref "mySNSTopic"          
        - !Ref "AWS::NoValue" 

也可以试试下面的形式:

  NotificationConfigurations:
    !If
      - IsProd
      - - NotificationTypes: 
            - "autoscaling:EC2_INSTANCE_LAUNCH_ERROR"
            - "autoscaling:EC2_INSTANCE_TERMINATE"
            - "autoscaling:EC2_INSTANCE_TERMINATE_ERROR"
          TopicARN: !Ref "mySNSTopic"          
      - !Ref "AWS::NoValue"  

请注意缩进。您可能需要调整它以匹配您的模板。