# encoding:utf-8
import boto3
import json
import os
from datetime import datetime, timedelta, timezone
def lambda_handler(event, context):
# 現在時刻
UTC = timezone(timedelta(hours=+0), 'UTC')
now = datetime.now(UTC)
# 期限
limit_hour = int(os.environ["limit_hour"])
# 対象インスタンスの取得
ec2 = boto3.resource("ec2")
result = ec2.instances.filter(
Filters=[{
"Name": "tag:limit_instance",
"Values": ["true"]
}]
)
# 起動中のインスタンスがあればチェック
for i in [i for i in result if i.state["Name"] == "running"]:
print("Instance ID [{0}] Launch Time [{1}]".format(i.instance_id, i.launch_time))
# 予定時間を過ぎている場合は削除
if (i.launch_time + timedelta(hours=limit_hour)) < now:
print("Instance ID [{0}] Limit".format(i.instance_id))
print(ec2.instances.filter(InstanceIds=[i.instance_id]).terminate())
else:
print("Instance ID [{0}] Not Limit".format(i.instance_id))
return "success"