I've wanted to make it for a long time, but when I thought it would be great to make it in Java, I haven't written about AWS Lambda being able to run in Python, so It's been 3 months since I decided to take on the challenge.
I tried it while various people wrote it.
Create a table in DynamoDB, tag information set for time and instance, Enter whether to start or stop.
Lambda Function (Python) runs every 10 minutes, If it matches the time of the data stored in DynamoDB, For all instances whose tag information matches Start or stop.
Create a table "EC2" in DynamoDB. There are four items. "Id" "Time" "Tag" "Start Stop".
Lambda Function(Python)
There are some points that I personally struggled with.
And the code is as follows.
import boto3
import datetime
from boto3.dynamodb.conditions import Key, Attr
def lambda_handler(event, context):
# create EC2 client
ec2 = boto3.client('ec2')
# get the time(%H:%M)
timeInfo = datetime.datetime.now().strftime("%H:%M")
tableInfoList = getTableInfoList(timeInfo)
instanceList = getInstanceStartStopList(ec2, tableInfoList)
executeInstanceStartStop(ec2, instanceList)
# get the list of data (Id, StartEnd, Tag, Time)
# Id : Sequence
# StartEnd : "start" or "stop"
# Tag : Tag-key
# Time : %H:%M ex) 09:00
# @param timeInfo
# @return list of data(Id, StartEnd, Tag, Time)
def getTableInfoList(timeInfo):
dynamodb = boto3.resource('dynamodb')
#Set TableName
table = dynamodb.Table('EC2')
#Send the Query
#Query Parameter
# @param TimeInfo : [hh:mm]
#TimeInfo = "09:00"
tableInfoList = table.scan(
FilterExpression=Attr('Time').eq(timeInfo)
)['Items']
return tableInfoList
# get the list of data (Start or Stop Instance Ids)
# @param ec2
# @param tableInfoList
# @return instanceList Dictionaly('start', 'stop')
def getInstanceStartStopList(ec2, tableInfoList):
startInstanceIdList = []
stopInstanceIdList = []
for tableInfo in tableInfoList:
for reservation in ec2.describe_instances(Filters=[{'Name':'tag-key','Values':[tableInfo['Tag']]}])["Reservations"]:
for instance in reservation["Instances"]:
if (tableInfo['StartStop'] == 'start'):
startInstanceIdList.append(instance["InstanceId"])
elif (tableInfo['StartStop'] == 'stop'):
stopInstanceIdList.append(instance["InstanceId"])
instanceList = {"start":startInstanceIdList, "stop":stopInstanceIdList}
return instanceList
# Start of Stop Instances
# @param ec2
# @param instanceList
def executeInstanceStartStop(ec2, instanceList):
startInstanceIdList = instanceList["start"]
stopInstanceIdList = instanceList["stop"]
if not len(startInstanceIdList) == 0:
ec2.start_instances(InstanceIds=startInstanceIdList)
if not len(stopInstanceIdList) == 0:
ec2.stop_instances(stopInstanceIdList)
I managed to do it with trial and error.
From now on, I'm thinking of making something that accompanies this.
I don't know when it will be. .. ..
Recommended Posts