#python #lambda
Вопрос:
У меня есть лямбда-функция для использования словаря для запуска графиков включения/выключения питания. В принципе, я определил время отключения питания для каждого дня в переменной словаря «app_off = {«Понедельник»: «20:52», «Вторник»: «22:00», «Среда»: «20:00», «Четверг»: «22:00», «Пятница’: ’20:00′}». Функция lambda запускается каждую минуту событием cloudwatch.
Предположительно, в определенное время дня (день недели) текущее время должно быть равно указанному времени в переменной словаря, а затем экземпляр ec2 отключился и включился. Но по какой-то причине моя лямбда-функция не сработала успешно. В файле журнала по-прежнему отображаются записи с «2021-04-26T20:24:42.925-07:00». Пожалуйста, помогите мне взглянуть, чтобы понять, где что-то не так.
import boto3
import time
ec2 = boto3.resource('ec2')
def lambda_handler(event, context):
# Get current time in format H:M
current_time = time.strftime("%H:%M")
current_dayoftheweek = time.strftime("%A")
print(f'The current time: {current_time}')
print(f'The current day of the week is: {current_dayoftheweek}')
# Find all the instances that are tagged with Scheduled:True
filters = [{
'Name': 'tag:Lambda_Managed',
'Values': ['Yes']
}
]
# Search all the instances which contains scheduled filter
instances = ec2.instances.filter(Filters=filters)
# Define different schedule groups and start/stop time.
# Application server schedule group
app_off = {'Monday': '20:52', 'Tuesday': '22:00', 'Wednesday': '20:00', 'Thursday': '22:00', 'Friday': '20:00'}
app_on = {'Monday': '5:00', 'Tuesday': '5:00', 'Wednesday': '7:00', 'Thursday': '5:00', 'Friday': '7:00', 'Saturday': '5:00'}
# Web server schedule group
web_off = {'Monday': '20:00', 'Tuesday': '22:00', 'Wednesday': '20:00', 'Thursday': '22:00', 'Friday': '20:00'}
web_on = {'Monday': '5:00', 'Tuesday': '5:00', 'Wednesday': '7:00', 'Thursday': '5:00', 'Friday': '7:00', 'Saturday': '5:00'}
# SQL server schedule group
sql_off = {'Monday': '20:00', 'Tuesday': '22:00', 'Wednesday': '20:00', 'Thursday': '22:00', 'Friday': '20:00'}
sql_on = {'Monday': '5:00', 'Tuesday': '5:00', 'Wednesday': '7:00', 'Thursday': '5:00', 'Friday': '7:00', 'Saturday': '5:00'}
# Stores list of instanceIDs
stopInstances = []
startInstances = []
# Locate all instances that are tagged to start or stop.
# ======crontab format===========
# App Schedule Group:
# minute hour (day of month) month (day of week)
# Power Off Triggers:
# 0 20 * * 1,3,5
# 0 22 * * 2,4
#
# Power On Triggers:
# 0 5 * * 1,2,4,6
# 0 7 * * 3,5
for instance in instances:
for tag in instance.tags:
if tag['Key'] == 'Schedule_Name':
if tag['Value'] == 'App' and current_time == app_off["current_dayoftheweek"]:
stopInstances.append(instance.id)
pass
if tag['Value'] == 'Web' and current_time == web_off["current_dayoftheweek"]:
stopInstances.append(instance.id)
pass
if tag['Value'] == 'Sql' and current_time == sql_off["current_dayoftheweek"]:
stopInstances.append(instance.id)
pass
if tag['Key'] == 'Schedule_Name':
if tag['Value'] == 'App' and current_time == app_on["current_dayoftheweek"]:
if instance.state['Name'] == 'stopped':
startInstances.append(instance.id)
pass
pass
if tag['Value'] == 'Web' and current_time == web_on["current_dayoftheweek"]:
if instance.state['Name'] == 'stopped':
startInstances.append(instance.id)
pass
pass
if tag['Value'] == 'Sql' and current_time == sql_on["current_dayoftheweek"]:
if instance.state['Name'] == 'stopped':
startInstances.append(instance.id)
pass
pass
pass
pass
#print('current_time')
print(f'The current time: {current_time}')
print(f'The current day of the week is: {current_dayoftheweek}')
# shut down all instances tagged to stop.
if len(stopInstances) > 0:
# perform the shutdown
stop = ec2.instances.filter(InstanceIds=stopInstances).stop()
print(f"Stopping instance: {stopInstances} - {current_time}")
else:
print("No instances to shutdown.")
# start instances tagged to stop.
if len(startInstances) > 0:
# perform the start
start = ec2.instances.filter(InstanceIds=startInstances).start()
print(f"Starting instance: {startInstances} - {current_time}")
else:
print("No instances to start.")
Комментарии:
1. Любой комментарий будет очень признателен, я застрял здесь на несколько дней. Cloudwatch был настроен на запуск один раз в минуту, и он действительно запускает функцию lambda.
2. Что вы наблюдаете вместо этого? Это ошибка? Это просто вообще не работает? Может быть, ваш триггер работает неправильно?