Search code examples
aws-cloudformationamazon-cloudwatchamazon-cloudwatch-metrics

How to define a CloudWatch Alarm on the sum of two metrics with CloudFormation?


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 ?


Solution

  • 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