트리거를 crontab 기반으로 설정하고 boto3 로 ec2 를 켜게 만듦
import json
import boto3
ec2 = boto3.client('ec2', 'ap-northeast-2')
def lambda_handler(event, context):
reservations = ec2.describe_instances()
ec2_list = []
ec2_list_start = []
ec2_list_stop = []
#인스턴스 조회
for attr in reservations["Reservations"]:
for instance in attr["Instances"]:
#인스턴스 태그 조회
for tag in instance["Tags"]:
#특정 태그 값 있는
if tag["Key"] == "AUTOSTATE" and tag["Value"] == "Y" :
ec2_list.append(instance)
for tagInstance in ec2_list:
#인스턴스가 실행중인경우
if tagInstance["State"]["Name"] == 'running':
ec2_list_start.append(tagInstance["InstanceId"])
ec2.stop_instances(InstanceIds=ec2_list_start)
print("stop...")
#인스턴스가 중지인경우
elif tagInstance["State"]["Name"] == 'stopped':
ec2_list_stop.append(tagInstance["InstanceId"])
ec2.start_instances(InstanceIds=ec2_list_stop)
print("start...")
else:
print("Nothing to see here")
아차, 인스턴스에는 AUTOSTATE 라는 태그를 달았다
어떤 놈을 끄고 켤지 표시하기 위해서..
더 좋은 방법이 있을테지만.. 난 바쁜 직장인이므로 이정도로 만족하고 잘 썼다
이제 필요가 없어서 종료!