背景:我每 15 分钟调用一个特定的 Lambda 函数来启动我的 EC2 实例。这通过查询标签的值来实现,如果该值与当前时间匹配,则将实例添加到要启动的实例列表中。
问题:但是,该函数大约每四个小时才工作一次,因为它由于被频繁调用而保持“温暖”状态。虽然函数是温暖的,但我当前时间的变量——调用时间——在温暖的环境中持久存在,并且永远不会更新到当前的、实际的、真实的、真实的时间。请参阅下面的代码。
# This lambda script start EC2 instances
import boto3
import logging
from datetime import datetime, time
ec = boto3.resource('ec2')
startup = datetime.now().strftime('%H%M')
now = int(startup)
minutes = [now-5,now-4,now-3,now-2,now-1,now]
logger = logging.getLogger()
logger.setLevel(logging.ERROR)
print 'The current time is: %s' % (startup)
def lambda_handler(event, context):
for min in minutes:
wave = ec.instances.filter(
Filters=[
{'Name': 'instance-state-name', 'Values': ['stopped']},
{'Name': 'tag:Autostop', 'Values': ['%d' % (min)]}
]
)
for i in wave:
iid = (i.instance_id)
for t in i.tags:
if t['Key'] == 'Autostop':
start_value = t['Value']
print 'Instance %s should be started at %s UTC' % (iid, start_value)
try:
print 'Starting %s' % (iid)
i.start()
except:
print 'ERROR -- Error starting instance %s' % (iid)
pass
在我的此功能的 CloudWatch 日志中,我看到一个新的日志流大约每四个小时出现一次,并且初始日志条目包含第 15 行的输出(当前时间是:X),但日志流中的每个后续条目都是只有 START 和 END requestids 而没有提及当前时间。这持续了大约四个小时,然后该功能似乎被回收并再次开始“冷”。
我是编程新手,想知道是否有办法确保我的基于时间的变量(startup 和now)每次都更新函数被调用,无论是热调用还是冷调用。
请您参考如下方法:
您需要将变量移动到 lambda_handler 函数中
def lambda_handler(event, context):
startup = datetime.now().strftime('%H%M')
now = int(startup)
minutes = [now-5,now-4,now-3,now-2,now-1,now]
for min in minutes:
[...]
