DEV Community

Cover image for Create CloudWatch Alarms with Python AWS CDK
chrishart0 for Signet Seal

Posted on

Create CloudWatch Alarms with Python AWS CDK

Create the alarm

Put this into your Python AWS CDK stack to create an alarm on a bucket asigned to a varibale named bucket

bucket = s3.Bucket...

s3_size_alarm = cloudwatch.Alarm(self, 'bucket_overloaded_alarm',
    metric= cloudwatch.Metric(
        namespace = "AWS/S3", 
        metric_name = "BucketSizeBytes",
        dimensions={
            "BucketName": bucket.bucket_name,
            "StorageType": "StandardStorage",
        },
        period = core.Duration.days(1),
        statistic="Maximum",
    ), 
    evaluation_periods=1, 
    threshold=1000000000 #1 GB
)
Enter fullscreen mode Exit fullscreen mode

This will create a CloudWatch alarm which:

  • Alarm if the size of the bucket goes over 1GB
  • Only monitors objects with the StandardStorage type

Relevant CDK docs:

Warning: Don't rely on an alarm watching the BucketSizeBytes metric to make sure your bucket doesn't grow too large. This metric is only collected once a day. Consider opting in to S3 request metrics for more in-depth S3 monitoring

Create alarm action

Alarms aren't very useful if they don't do anything. Setup some actions:

topic = sns.Topic.from_topic_arn(self,'snstopic',"arn:aws:sns:us-east-1:123456789012:alarm-go-ahhhhhhhhhhhh")

s3_size_alarm.add_alarm_action(
    cloudwatch_actions.SnsAction(
        topic = topic
    )
)
Enter fullscreen mode Exit fullscreen mode

Relevant CDK docs:

More CDK or AWS Serverless Questions?

Feel free to leave a comment here or hit us up on LinkedIn.

Want to learn more about how SignetSeal can help make your chats more secure? Read more about us on our website

Discussion (0)