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.

已提问 1 年前675 查看次数
2 回答
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
已回答 1 年前
  • 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
已回答 1 年前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则