如何通过CDK创建EventBridge Rules数量达阈值触发的告警?
用AWS CDK实现Event Bus规则数量告警
实现思路
借助CloudWatch内置的AWS/Events命名空间下的RuleCount指标,针对指定Event Bus的规则数量设置告警阈值,当数量达到设定值时触发通知动作。
CDK代码实现(TypeScript示例)
以下是完整的实现代码,包含指标定义、告警配置以及SNS通知动作:
import { Stack, StackProps, Duration } from 'aws-cdk-lib'; import { Construct } from 'constructs'; import * as events from 'aws-cdk-lib/aws-events'; import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch'; import * as sns from 'aws-cdk-lib/aws-sns'; import * as cloudwatch_actions from 'aws-cdk-lib/aws-cloudwatch-actions'; export class EventBusRuleCountAlarmStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props); // 1. 引用目标Event Bus(默认总线示例,自定义总线可替换为自身创建的实例) const targetEventBus = events.EventBus.fromEventBusName(this, 'TargetEventBus', 'default'); // 2. 创建CloudWatch指标:统计指定Event Bus的规则数量 const ruleCountMetric = new cloudwatch.Metric({ namespace: 'AWS/Events', metricName: 'RuleCount', dimensionsMap: { EventBusName: targetEventBus.eventBusName, }, statistic: 'Maximum', period: Duration.minutes(5), }); // 3. 创建SNS主题,用于接收告警通知(可订阅邮箱、Lambda等终端) const alarmTopic = new sns.Topic(this, 'EventBusRuleCountAlarmTopic', { displayName: 'Event Bus Rule Count Alarm Topic', }); // 4. 创建CloudWatch告警 new cloudwatch.Alarm(this, 'EventBusRuleCountAlarm', { alarmName: `EventBus-${targetEventBus.eventBusName}-RuleCount-Alarm`, alarmDescription: `当Event Bus ${targetEventBus.eventBusName}的规则数量达到100时触发告警`, metric: ruleCountMetric, threshold: 100, evaluationPeriods: 1, comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, actionsEnabled: true, }).addAlarmAction(new cloudwatch_actions.SnsAction(alarmTopic)); } }
关键说明
- 指标维度:必须指定
EventBusName维度,确保仅统计目标总线的规则数量,避免混淆其他总线数据。 - 统计方式:选择
Maximum统计值,因为规则数量是离散的增减数值,最大值能准确反映当前规则总数。 - 告警动作:示例用SNS主题作为告警接收端,可根据需求替换为Lambda函数、Slack集成等其他动作。
- 阈值调整:可根据自身需求修改
threshold参数,比如设置为硬限制300的80%(240)作为预警阈值。
内容的提问来源于stack exchange,提问作者Arpan Dutta
相关产品推荐
相关产品推荐

