4

I need to trigger an alarm when the sum of the same metric (ApproximateNumberOfMessagesVisible) on two different queues exceed the value of 100

In September '17, this answer stated that the only way to do it was with a Lambda function getting the two values and summing them up via CloudWatch API.

At writing time, Feb. '19, it is possible to use "Metric Math", so there is no need to have a lambda function or an EC2 instance. Is it possible to use Metric Math to define an Alarm directly in CloudFormation ?

Ing. Luca Stucchi
  • 3,070
  • 6
  • 36
  • 58

1 Answers1

9

It is actually possible to implement the Alarm logic directly in CloudFormation.

Assuming to have two Scaling Policies ECSScaleUp and ECSScaleDown, the alarm definition will look like:

ECSWorkerSQSCumulativeAlarm:
  Type: AWS::CloudWatch::Alarm
  Properties:
    AlarmName: !Join ['-', [!Ref 'MyService', 'SQSCumulativeAlarm']]
    AlarmDescription: "Trigger ECS Service Scaling based on TWO SQS queues"
    Metrics:
      - Id: e1
        Expression: "fq + sq"
        Label: "Sum of the two Metrics"
      - Id: fq
        MetricStat:
          Metric:
            MetricName: ApproximateNumberOfMessagesVisible
            Namespace: AWS/SQS
            Dimensions:
              - Name: QueueName
                Value: !GetAtt [ FirstQueue, QueueName]
        Period: 60
        Stat: Average
        Unit: Count
        ReturnData: false
      - Id: sq
        MetricStat:
          Metric:
            MetricName: ApproximateNumberOfMessagesVisible
            Namespace: AWS/SQS
            Dimensions:
              - Name: QueueName
                Value: !GetAtt [ SecondQueue, QueueName]
          Period: 60
          Stat: Average
          Unit: Count
        ReturnData: false
    EvaluationPeriods: 2
    Threshold: 100
    ComparisonOperator: GreaterThanThreshold
    AlarmActions:
      - !Ref ECSScaleUp
      - !Ref ECSScaleDown
    OKActions:
      - !Ref ECSScaleUp
      - !Ref ECSScaleDown
Ing. Luca Stucchi
  • 3,070
  • 6
  • 36
  • 58
  • Under the "fq" MetricDataQuery the Period, Stat and Unit fields should be indented another two spaces so they're part of the MetricStat child rather than the MetricDataQuery. – markshep Jun 20 '22 at 15:49