使用Boto3遍历EC2实例标签时出现重复操作的问题
问题分析与修复方案
问题根源
你的代码逻辑是逐个遍历实例的标签,只要某个标签不匹配TurnOff=False,就立刻执行“要停止”的操作;当遍历到匹配的标签时,又执行“不停止”的操作。这就导致有多个标签的实例会触发两次输出——比如i-1的第一个标签env=prod不匹配,进入else打印停止提示,第二个标签匹配又打印不停止提示。
修复方案
正确的逻辑应该是:先遍历所有标签,检查是否存在TurnOff=False的标签,遍历完成后再根据结果决定执行哪种操作,而不是在遍历过程中逐个判断输出。
修正后的代码:
response = client_ec2.describe_instances( Filters=[ { "Name": "instance-state-name", "Values": ["running"] },]) session = boto3.Session(region_name="us-west-2") region = "us-west-2" for reservation in response["Reservations"]: for instance in reservation["Instances"]: CPUUtilization = client_cw.get_metric_statistics( Namespace='AWS/EC2', MetricName='CPUUtilization', Dimensions=[{'Name': 'InstanceId', 'Value': instance["InstanceId"]}], StartTime=past, EndTime=now, Period=600, Statistics=['Average'] ) datapoints = CPUUtilization['Datapoints'] last_datapoint = sorted(datapoints, key=itemgetter('Timestamp'))[-1] utilization = last_datapoint['Average'] load = round(utilization, 1) timestamp = str(last_datapoint['Timestamp']) if load < 10: InstanceID = instance["InstanceId"] # 初始化标志位,标记是否找到目标标签 found_turnoff_false = False # 遍历所有标签,仅负责检查是否存在目标标签 for tag in instance["Tags"]: if tag['Key'] == "TurnOff" and tag['Value'] == "False": found_turnoff_false = True break # 找到后提前退出遍历,提升效率 # 遍历结束后统一判断执行操作 if found_turnoff_false: print("TurnOff False tag found. This instance will NOT be stopped") print(f"CPU Utilization more than 0% on {InstanceID}\n") else: print("TurnOff False tag not found. This instance WILL be stopped") print(f"CPU Utilization more than 0% on {InstanceID}\n")
关键调整说明
- 新增
found_turnoff_false标志位,先完成所有标签的检查,确认是否存在目标标签 - 遍历标签阶段只负责设置标志,不直接输出操作结果
- 遍历结束后统一根据标志判断输出,确保每个实例只会触发一次操作提示
内容的提问来源于stack exchange,提问作者Oleksadr S
相关产品推荐
相关产品推荐

