Search code examples
jsonyamlaws-cloudformationaws-event-bridge

AWS CloudFormation: EventBridge rule's event pattern is not formatted as needed


I have this CloudFormation snippet for an AWS EventBridge Rule:

  AutoscalingRule:
    Type: AWS::Events::Rule
    Properties:
      Description: "AutoscalingRule"
      EventPattern:
        source:
          - aws.autoscaling
        detail:
          - !Sub "AutoScalingGroupName: ${AutoscalingGroup}"
        detail-type:
          - "EC2 Instance Launch Successful"
          - "EC2 Instance Terminate Successful"
      State: "ENABLED"
      Targets:
        -
          Arn:
            Fn::GetAtt:
              - "AutoscalingMonitoringLambda"
              - "Arn"
          Id: "autoscaling-monitoring"

The problem is that for Event Pattern, the detail section is not formatted as it should have been if created from the Console. If created from the console, the detail section looks like this:

{
  "source": ["aws.autoscaling"],
  "detail-type": ["EC2 Instance Launch Successful", "EC2 Instance Terminate Successful"],
  "detail": {
    "AutoScalingGroupName": ["test"]
  }
}

but when deployed through CloudFormation it looks like this:

{
  "detail-type": ["EC2 Instance Launch Successful", "EC2 Instance Terminate Successful"],
  "source": ["aws.autoscaling"],
  "detail": ["AutoScalingGroupName: test"]
}

I have tried inserting it as JSON or formatting it manually but it doesn't work.

Any idea on how I should add the detail section to be the same as the one created in the Console.


Solution

  • The "detail" section, in your Cloudformation template, is a YAML array, so it's traduced correctly in a JSON Array.

    To fix it, change the EventPattern section to:

    EventPattern:
        source:
          - aws.autoscaling
        detail:
          AutoScalingGroupName:
            - !Ref AutoscalingGroup
        detail-type:
          - "EC2 Instance Launch Successful"
          - "EC2 Instance Terminate Successful"
    

    For further doubts on JSON -> YAML conversion, try: https://www.json2yaml.com/