CloudFormation:有条件的 AutoScalingGroup 通知

Posted

技术标签:

【中文标题】CloudFormation:有条件的 AutoScalingGroup 通知【英文标题】:CloudFormation: conditional AutoScalingGroup notifications 【发布时间】:2020-08-21 02:47:05 【问题描述】:

我想使用 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"

【问题讨论】:

【参考方案1】:

使用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"  

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

【讨论】:

以上是关于CloudFormation:有条件的 AutoScalingGroup 通知的主要内容,如果未能解决你的问题,请参考以下文章

在 CloudFormation 模板中否定条件

AWS CloudFormation 条件模板验证

CloudFormation,在 DependsOn 上应用条件

如何根据 IAM 角色 CloudFormation 模板中的参数提供不同的条件

Visual Studio调试器指南----Autos窗口

OLX Autos的二手车交易额达到10亿美元