Delete old alarms with not resource

0

The idea is to find a way to identify old alarms with non-existent resources and possibly delete them.

2 Answers
1

Hey Nicolas,

Are you referring to cloudwatch alarms? Are you familiar with lambda? At a high level, I would recommend creating a lambda function with a trigger from eventbridge that will delete the alarm when a resource is no longer associated with the alarm.

Cloud_G
answered a year ago
  • Yes when I am refering to alarm are CloudWatch Alarm, my point is which could be the best way to identify a CloudWatch alarm whihc is not in use becouse the resource where thre metrics come has been remove.

0

Makes sense. Leveraging Lambda would be your best option to accomplish that. Since lambda can be triggered by cloudtrail (which logs all API calls) or cloudwatch or eventbridge, you can have lambda remove those alarms. You could also create a function that routinely runs on a cron job that first calls all the cloudwatch alarms and lists them all, and using "if" statements, deletes alarms that do not have resources associated. Below is an example that you may want to try using as a base template:


import boto3

def lambda_handler(event, context):
    # Create a CloudWatch client
    cloudwatch = boto3.client("cloudwatch")

    # List all CloudWatch alarms
    alarms = cloudwatch.describe_alarms()

    # Create an EC2 client
    ec2 = boto3.client("ec2")

    # Iterate over the alarms
    for alarm in alarms["MetricAlarms"]:
        # Check if the alarm is associated with an EC2 instance
        if alarm["Namespace"] == "AWS/EC2" and alarm["Dimensions"]:
            dimension = alarm["Dimensions"][0]
            if dimension["Name"] == "InstanceId":
                # Retrieve the EC2 instance
                instance_id = dimension["Value"]
                instances = ec2.describe_instances(InstanceIds=[instance_id])
                if not instances["Reservations"]:
                    # The instance does not exist, delete the alarm
                    cloudwatch.delete_alarms(AlarmNames=[alarm["AlarmName"]])
Cloud_G
answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions