Titulum
Titulum

Reputation: 11446

CloudFormation: conditional AutoScalingGroup notifications

I want to receive AutoScaling Event notifications using SNS, but only in my PROD environment. How can I configure my CloudFormation template to do so?

Should it be like this:

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: "[email protected]"
          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:

Or does CloudFormation support the following too:

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: "[email protected]"
          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"

Upvotes: 2

Views: 352

Answers (1)

Marcin
Marcin

Reputation: 238051

It should be double using Fn::If function:

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

Can also try the following form:

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

Please be careful about indentation. You may need to adjust it to match your template.

Upvotes: 2

Related Questions