Since there are a large number of EC2 instances that I usually use for development and testing, I use cron to schedule startup and stop of instances, and use them at the lowest possible cost. I haven't touched AWS Lambda at all, so I thought it was a good opportunity to migrate from cron batch, so I made some changes for AWS Lambda, so I will expose it.
** "I want to start the instance used for development etc. only during business hours" **, ** "I want to start it regularly only on a specific day of the week" **. To set the instance, just put the tag written in the configuration file in the tag of the instance, and delete the tag to release it.
Since the libraries boto and pytz are required, install them in the same layer as ec2_scheduler.py.
$ pip install boto -t path/to/ec2_scheduler/
$ pip install pytz -t path/to/ec2_scheduler/
Only instances with the same tags as tag-key and tag-value in the configuration file are scheduled to be executed. If you want to stop the scheduled execution, just delete the tag.
The setting items are as follows (file name can be changed)
schedule.cfg
[Develop]
region: ap-northeast-1 <=region
type: daily <=Execution Type(Since there is only daily, it is as it is)
tag-key: AWS-Schedule <=Instance tag name
tag-value: Dev-Weekday <=Tag value
start: 9:00 <=Start-up
stop: 19:00 <=Stop
skip: saturday, sunday <=Specify the day to skip by day of the week
timezone: Asia/Tokyo <=Time zone specification
↓ You can set multiple schedules in the configuration file.
[TestServer]
region: ap-northeast-1
...
...
lambda_function.py
# -*- coding: utf-8 -*-
from ec2_scheduler import EC2Scheduler
def lambda_handler(event, context):
access_id = 'AWS access ID'
secret_key = 'AWS secret key'
conf = 'schedule.cfg'
schedule = EC2Scheduler(access_id=access_id, secret_key=secret_key, conf=conf)
schedule.job()
When you have prepared the Lambda Function, zip the prepared file. (Run in the same directory)
cd path/to/ec2_scheduler
zip -r ec2_scheduler.zip .
Create a new Lambda Function in AWS Lambda in the AWS Management Console [Lambda] ** Select [Create a Lambda function]-> [Python2.7]-> [lambda canary] ** [Configure event sources] ** Select [Event source type]-> [CloudWatch Events --Schedule] ** ** Enter a name in [Rule name] ** as appropriate ** Select the execution schedule with [Schedule expression] ** [Configure function] A suitable name for ** [Name] ** [Runtime] -> [Python 2.7] ** Upload the zip file prepared in advance with [Lambda function code]-> [Upload a .ZIP file] ** Put the handler name in ** [Handler \ *] ** ("lambda_function.lambda_handler" in the example) [Role] -> [Basic execution role] ** [Advanced settings] ** Make appropriate settings
The rest should be created with ** [Create function] **
After creating a Lambda Function, check it with Test. The Test should be succeeded, so all you have to do is set the ScheduleEvent you set earlier in ** [Event source] ** to ** State Enabled **.
Recommended Posts