[英]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. 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.此代码可以很好地删除警报,但是当我查看 CloudWatch 日志组中 Lambda 函数的执行日志时,我可以看到多次为同一个 CloudWatch 警报创建了大量事件。
Please help me to fix this code.请帮助我修复此代码。
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:然而:
print()
statement is printing instanceID
rather than instance
print()
语句正在打印instanceID
而不是instance
instance
循环中的任何内容实际上都没有引用instance
The fact is, instanceID
is a string that contains one Instance ID , as can be seen when printing GetAlarmNamePrefix
.事实上, instanceID
是一个包含一个 Instance ID的字符串,正如在打印GetAlarmNamePrefix
时可以看到的那样。
Therefore, you can remove the for
loop.因此,您可以删除for
循环。
It is possible that multiple events are being passed to the Lambda function.可能有多个事件正在传递给 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.但是,没有显示提取event
的代码部分,因此我无法评论是否应该更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.