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.

preguntada hace un año675 visualizaciones
2 Respuestas
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
respondido hace un año
  • 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
respondido hace un año

No has iniciado sesión. Iniciar sesión para publicar una respuesta.

Una buena respuesta responde claramente a la pregunta, proporciona comentarios constructivos y fomenta el crecimiento profesional en la persona que hace la pregunta.

Pautas para responder preguntas