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 年前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南