This is the AWS CDK v2 Developer Guide. The older CDK v1 entered maintenance on June 1, 2022 and ended support on June 1, 2023.
Use the aws-cloudwatch package to set up Amazon CloudWatch alarms on CloudWatch metrics. You can use predefined metrics or create your own.
Use an existing metric
Many AWS Construct Library modules let you set an alarm on an existing metric by passing the metric's name to a convenience method on an instance of an object that has metrics. For example, given an Amazon SQS queue, you can get the metric ApproximateNumberOfMessagesVisible from the queue's metric() method:
const metric = queue.metric("ApproximateNumberOfMessagesVisible");
Create your own metric
Create your own metric as follows, where the namespace value should be something like AWS/SQS for an Amazon SQS queue. You also need to specify your metric's name and dimension:
const metric = new cloudwatch.Metric({
namespace: 'MyNamespace',
metricName: 'MyMetric',
dimensionsMap: { MyDimension: 'MyDimensionValue' }
});
Create the alarm
Once you have a metric, either an existing one or one you defined, you can create an alarm. In this example, the
alarm is raised when there are more than 100 of your metric in two of the last three evaluation periods. You can use
comparisons such as less-than in your alarms via the comparisonOperator
property. Greater-than-or-equal-to
is the AWS CDK default, so we don't need to specify it.
const alarm = new cloudwatch.Alarm(this, 'Alarm', {
metric: metric,
threshold: 100,
evaluationPeriods: 3,
datapointsToAlarm: 2,
});
An alternative way to create an alarm is using the metric's createAlarm()
method, which takes essentially the same properties as the Alarm
constructor. You don't need to pass in
the metric, because it's already known.
metric.createAlarm(this, 'Alarm', {
threshold: 100,
evaluationPeriods: 3,
datapointsToAlarm: 2,
});