BACKGROUND: I invoke a specific Lambda function every 15 minutes to start my EC2 instances. This works by querying the value of a tag and if that value matches the current time, the instances is added to a list of instances to be started.
PROBLEM: However, the function only works about once every four hours because it stays "warm" due to being invoked so often. While the function is warm, the variable I have for the current time - the time of invocation - is persisted in the warm environment and never gets updated to the current, actual, for-really-real-realsies time. See code below.
# 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
In my CloudWatch logs for this function, I see a new log stream appear about every four hours and the initial log entry contains the output of line 15 (The current time is: X) but every subsequent entry in the log stream is just the START and END requestids and no mention of the current time. This goes on for about four hours and then the function appears to be recycled and starts "cold" all over again.
I'm relatively new to programming and would like to know if there's a way to make sure my time-based variables (startup and now) are updated every time the function is invoked, whether it's a warm or cold invocation.