if条件满足时else仍执行:带skip_shutdown标签的EC2实例异常关机排查
EC2实例skip_shutdown标签不生效修复方案
问题根因
- 标签键大小写不匹配:脚本读取标签时严格匹配全小写
skip_shutdown,若实际实例标签键为Skip_Shutdown/SKIP_SHUTDOWN等大小写混合格式,会读取失败得到None,导致skip_shutdown == 'yes'判断不通过,实例被加入关机列表 - 标签值存在冗余空格:若实例标签值设为
yes(末尾带空格)、Yes(开头带空格/大写),未做预处理会导致匹配失败 - 逻辑遗漏:关机逻辑未对齐开机逻辑做节假日校验,节假日会正常执行关机(可选修复)
修复点
- 标签读取时统一对键转小写,值做trim和小写处理,兼容大小写、空格问题
- 关机逻辑增加节假日校验,和开机逻辑对齐
- 修复代码中HTML转义的引号问题,保证可直接运行
- 优化重复代码结构,降低维护成本
修复后完整代码
import boto3 import time from datetime import datetime import dateutil.tz import os import ast ec2 = boto3.resource('ec2') def lambda_handler(event, context): pacific = dateutil.tz.gettz('America/Los_Angeles') time_format='%H:%M' date = datetime.now(tz=pacific) print(f'Current PST time is: {date.strftime(time_format)}') current_time = date.strftime(time_format) current_dayoftheweek = date.strftime("%A") print(f'The current day of the week is: {current_dayoftheweek}') # 节假日逻辑 day_format='%m:%d' current_date = date.strftime(day_format) holidays = os.environ['holidays'] print(f'The current date is: {current_date}') print(f'The defined holidays is: {holidays}') def Convert(string): li = list(string.split(",")) return li holidays = Convert(holidays) typeofholiday = type(holidays) print(f'The data type of the variable holidays is {typeofholiday}') # 过滤托管实例 filters = [{ 'Name': 'tag:Lambda_Managed', 'Values': ['Yes'] }] instances = ec2.instances.filter(Filters=filters) # 加载各分组调度时间 app_off = ast.literal_eval(os.environ['app_off']) app_on = ast.literal_eval(os.environ['app_on']) web_off = ast.literal_eval(os.environ['web_off']) web_on = ast.literal_eval(os.environ['web_on']) sql_off = ast.literal_eval(os.environ['sql_off']) sql_on = ast.literal_eval(os.environ['sql_on']) stopInstances = [] startInstances = [] def check(list1, val): for x in list1: if val == x: return True return False is_holiday = check(holidays, current_date) for instance in instances: Schedule_Name = None skip_shutdown = False # 兼容标签大小写、空格问题 for tag in instance.tags: tag_key = tag['Key'].strip().lower() tag_value = tag['Value'].strip().lower() if tag_key == 'schedule_name': Schedule_Name = tag['Value'].strip() elif tag_key == 'skip_shutdown': skip_shutdown = (tag_value == 'yes') # 关机逻辑 off_time = None if Schedule_Name == 'App': off_time = app_off.get(current_dayoftheweek) elif Schedule_Name == 'Web': off_time = web_off.get(current_dayoftheweek) elif Schedule_Name == 'Sql': off_time = sql_off.get(current_dayoftheweek) if off_time and current_time == off_time and not is_holiday: if skip_shutdown: # 重置标签为no instance.create_tags(Tags=[{"Key": 'skip_shutdown',"Value": 'no'}]) else: stopInstances.append(instance.id) # 开机逻辑 on_time = None if Schedule_Name == 'App': on_time = app_on.get(current_dayoftheweek) elif Schedule_Name == 'Web': on_time = web_on.get(current_dayoftheweek) elif Schedule_Name == 'Sql': on_time = sql_on.get(current_dayoftheweek) if on_time and current_time == on_time and not is_holiday: startInstances.append(instance.id) # 执行关机 if len(stopInstances) > 0: stop = ec2.instances.filter(InstanceIds=stopInstances).stop() print(f"Stopping instance: {stopInstances} - {current_time}") else: print("No instances to shutdown.") # 执行开机 if len(startInstances) > 0: start = ec2.instances.filter(InstanceIds=startInstances).start() print(f"Starting instance: {startInstances} - {current_time}") else: print("No instances to start.")
内容的提问来源于stack exchange,提问作者condescendent
相关产品推荐
相关产品推荐

