如何通过CloudFormation用Metric Math定义两队列指标求和的CloudWatch告警?
Can I Use Metric Math in CloudFormation to Trigger an Alarm When the Sum of Two SQS Queue Metrics Exceeds 100?
Absolutely yes! You can define this alarm directly in CloudFormation using Metric Math—no Lambda or EC2 instances needed, taking full advantage of the CloudWatch features rolled out in February 2019. This replaces the older Lambda-based approach you mentioned from 2017, making the setup far simpler and more maintainable.
Here's a CloudFormation YAML Example
This template creates a CloudWatch alarm that triggers when the sum of ApproximateNumberOfMessagesVisible across two different SQS queues exceeds 100:
Resources: QueueMessageSumAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmName: "SQS-Queue-Message-Sum-Exceeds-100" AlarmDescription: "Triggers when total visible messages across two queues exceed 100" ComparisonOperator: GreaterThanThreshold Threshold: 100 EvaluationPeriods: 1 DatapointsToAlarm: 1 MetricDataQueries: # Query 1: Get visible messages from first queue - Id: "q1" MetricStat: Metric: Namespace: "AWS/SQS" MetricName: "ApproximateNumberOfMessagesVisible" Dimensions: - Name: QueueName Value: !Ref FirstQueueName # Replace with your first queue name Period: 60 Stat: Sum ReturnData: false # Query 2: Get visible messages from second queue - Id: "q2" MetricStat: Metric: Namespace: "AWS/SQS" MetricName: "ApproximateNumberOfMessagesVisible" Dimensions: - Name: QueueName Value: !Ref SecondQueueName # Replace with your second queue name Period: 60 Stat: Sum ReturnData: false # Query 3: Calculate sum of q1 and q2 - Id: "sum_query" Expression: "SUM(q1, q2)" ReturnData: true AlarmMetricQuery: Id: "sum_query"
Key Details Explained
- MetricDataQueries: This section defines the three queries needed:
q1andq2: Fetch theApproximateNumberOfMessagesVisiblemetric for each of your SQS queues. We setReturnData: falsebecause we don't need these individual metrics for the alarm itself—only their sum.sum_query: Uses theSUM()expression to add the results ofq1andq2. SettingReturnData: truetells CloudWatch this is the metric the alarm should evaluate.
- AlarmMetricQuery: Points to the
sum_queryID, so the alarm uses the summed value for its threshold check. - Threshold & ComparisonOperator: Set to trigger when the summed value goes above 100.
This approach is clean, serverless, and eliminates the overhead of managing a Lambda function just to calculate a metric sum.
内容的提问来源于stack exchange,提问作者Ing. Luca Stucchi
相关产品推荐
相关产品推荐

