amazon-web-servicesaws-lambdaamazon-cloudwatchcloudwatch-alarms

CloudWatch auto alarm deletion executing multiple times


I have a piece of python script that is running in an AWS Lambda function that deletes a CloudWatch alarm when an EC2 instance is going to the Stopped state.

elif    'source' in event and event['source'] == 'aws.ec2' and event['detail']['state'] == 'stopped':
        instanceID = event['detail']['instance-id']
        GetAlarmNamePrefix = "AutoAlarm-" + instanceID
        print(GetAlarmNamePrefix)
        for instance in instanceID:
            print("deleting alarms for instance :" + instanceID)
            AlarmNamePrefix = GetAlarmNamePrefix
            response = cloudwatch.describe_alarms(AlarmNamePrefix=AlarmNamePrefix,)
            alarm_list = []
            if 'MetricAlarms' in response:
                for alarm in response['MetricAlarms']:
                    alarm_name = alarm['AlarmName']
                alarm_list.append(alarm_name)
                print(alarm_list)
                cloudwatch.delete_alarms(AlarmNames=alarm_list)

This code is deleting the alarms fine but when I look at the Lambda function's execution logs in the CloudWatch Log Group I could see there is a huge number of events created for the same CloudWatch alarm multiple times.

Please help me to fix this code.

Please see the screenshot attached for from log groups


Solution

  • Take a look at these lines:

            instanceID = event['detail']['instance-id']
            GetAlarmNamePrefix = "AutoAlarm-" + instanceID
            print(GetAlarmNamePrefix)
            for instance in instanceID:
                print("deleting alarms for instance :" + instanceID)
    

    In theory, it is looping through each instance. However:

    The fact is, instanceID is a string that contains one Instance ID, as can be seen when printing GetAlarmNamePrefix.

    Therefore, you can remove the for loop.

    It is possible that multiple events are being passed to the Lambda function. However, the section of your code that extracts the event is not shown, so I can't comment on whether that should be changed.