如何为CloudWatch仪表盘添加带告警注释的图表部件并解决校验错误
问题原因
- CloudWatch 图形部件(
GraphWidget)不支持仅配置告警注释,必须至少绑定一个指标作为数据源,服务端校验要求部件必须包含metrics或insightRule属性,你的代码只传了告警注释,没有指定指标,因此触发校验失败。 cdk synth仅做本地语法和类型校验,不会校验云服务端的业务规则,所以本地合成可以正常通过,只有部署到AWS时才会报错。
解决方案
第一步:修改MetricAlarm类,暴露内部创建的指标对象
import { Alarm, DimensionHash, Metric, Statistic, Unit, } from '@aws-cdk/aws-cloudwatch'; import { Construct } from '@aws-cdk/core'; export class MetricAlarm { public readonly alarm: Alarm; // 新增:暴露指标对象供仪表盘部件使用 public readonly metric: Metric; constructor(scope: Construct, id: string, { namespace, metricName, label, dimensions, statistic = Statistic.AVERAGE, threshold, alarmName, alarmDescription, unit = Unit.COUNT, evaluationPeriods = 1, }: MetricAlarmProps) { this.metric = new Metric({ namespace, metricName, label, dimensions, statistic, unit, }); this.alarm = this.metric.createAlarm(scope, id, { evaluationPeriods, threshold, alarmName, alarmDescription, }); } }
第二步:修改AlarmMetricWidget类,增加指标入参并绑定到部件
import { GraphWidget, IMetric } from '@aws-cdk/aws-cloudwatch'; // AlarmMetricWidgetProps 定义新增metric字段 export default class AlarmMetricWidget extends GraphWidget { constructor({ alarmAnnotation, title, size = 'standard', metric // 新增:指标参数 }: AlarmMetricWidgetProps) { super({ title, leftAnnotations: [alarmAnnotation], // 绑定指标到部件,满足服务端校验要求 leftMetrics: [metric], width: (size === 'wide' ? 12 : 6), }); } }
第三步:修改调用代码,传入指标参数
// 此处已预先定义好dashboard对象 const ecsServiceAlarm = new ECSServiceAlarm(scope, id, { namespace: 'AWS/ECS', metricName: 'CPUUtilization', statistic: Statistic.AVERAGE, dimensions: { ClusterName: ecsClusterName, ServiceName: ecsServiceName, }, label, threshold, alarmName, alarmDescription, }); const widget = new AlarmMetricWidget({ alarmAnnotation: ecsServiceAlarm.alarm.toAnnotation(), // 传入指标 metric: ecsServiceAlarm.metric, title: 'My alarm widget', }); dashboard.addWidgets(widget);
修改后重新部署即可正常通过校验,部件会同时展示指标趋势和告警阈值线,符合使用预期。
内容的提问来源于stack exchange,提问作者phuwin
相关产品推荐
相关产品推荐

