본문 바로가기
CSP (Cloud Service Provider)/AWS

EC2 Instance Scheduler

by HemMu 2022. 12. 22.

EC2를 계속 켜놓게 되면 요금이 나온다. EC2를 업무시간에만 사용하는 경우나 일정시간에만 사용하는 경우에 인스턴스스케줄링을 통해 인스턴스 사용 시간을 줄여 비용을 절약할 수 있습니다.

import boto3
region = 'ap-northeast-2'
instances = []
ec2_r = boto3.resource('ec2')
ec2 = boto3.client('ec2', region_name=region)

for instance in ec2_r.instances.all():
    for tag in instance.tags:
        if tag['Key'] == "hamster":
            if tag['Value'] == "cute":
                instances.append(instance.id)

def lambda_handler(event, context):
    ec2.stop_instances(InstanceIds=instances)
    print('stopped your instances: ' + str(instances))

다음은 Lambda를 이용하여 스케쥴링하는 Python 코드입니다.

region = 'ap-northeast-2'

tag['Key'] == "hamster"

if tag['Value'] == "cute"

 

ap-northeast-2 (서울리전)의 EC2 tag의 key값이 hamster이며 tag value가 cute인 EC2를 종료합니다.

 

주기적으로 Lambda를 실행하고 싶으면 CloudWatch의 EventBridge에서 

 

Event bus : default
Rule type : Schedule

GMT 기준 cron 표현식으로 원하는 시간 설정

target types : AWS service
Select a target : Lambda function
Function : 앞서 만든 Lambda Function 선택

 

해준다.

'CSP (Cloud Service Provider) > AWS' 카테고리의 다른 글

AWS Step Functions  (0) 2022.12.26
CPU/디스크/메모리 (2)  (1) 2022.12.22
IAM Billing에 대한 액세스 거부  (0) 2022.12.22
[AWS] Lambda  (0) 2022.12.22
AWS Windows 서버 설치 및 접속방법  (0) 2022.12.21

댓글