AWS-CDK Example of CloudWatch Alarm with Anomaly detection

Viewed 6225

Can someone provide a generic example of AWS Cloudwatch Alarm based on Anomaly Detection of a metric built with AWS CDK in Python3?

I have tried mapping aws cloudformation example of it to aws_cdk.aws_cloudwatch.Alarm and aws_cdk.aws_cloudwatch.CfnAlarm with little to no luck.

2 Answers

Eventually managed to make anomaly detection work with CfnAlarm

from aws_cdk import (
    aws_sns as sns,
    aws_cloudwatch as cw,
    core
)

anomaly_detector = cw.CfnAnomalyDetector(
    self, "AnomalyDetector",
    metric_name="my_metric",
    namespace="my_namespace",
    stat="Sum"
)

slack_topic = sns.Topic(self, "AnomalySns",
                        display_name="anomaly-sns",
                        topic_name="anomaly-sns"
                        )

anomaly_cfnalarm = cw.CfnAlarm(self, "AnomalyAlarm",
                               actions_enabled=True,
                               alarm_actions=[slack_topic.topic_arn],
                               alarm_description="<..>",
                               alarm_name="AnomalyAlarm",
                               comparison_operator="LessThanLowerOrGreaterThanUpperThreshold",
                               datapoints_to_alarm=1,
                               evaluation_periods=1,
                               insufficient_data_actions=[slack_topic.topic_arn],
                               metrics=[
                                   cw.CfnAlarm.MetricDataQueryProperty(
                                       expression="ANOMALY_DETECTION_BAND(m1, 2)",
                                       id="ad1"
                                   ),
                                   cw.CfnAlarm.MetricDataQueryProperty(
                                       id="m1",
                                       metric_stat=cw.CfnAlarm.MetricStatProperty(
                                           metric=cw.CfnAlarm.MetricProperty(
                                               metric_name=anomaly_detector.metric_name,
                                               namespace=anomaly_detector.namespace
                                           ),
                                           period=core.Duration.minutes(5).to_seconds(),
                                           stat="Sum"
                                       )
                                   )
                               ],
                               ok_actions=[slack_topic.topic_arn],
                               threshold_metric_id="ad1",
                               treat_missing_data="breaching"
                               )

This is partially based on AWS Docs CloudFormation example of Cloudwatch Anomaly Alarm https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html

Related