[AWS] Lambda를 사용하여 EC2 목록에 있는 모든 인스턴스 중지하기

pokcha's·2024년 1월 3일
0

aws

목록 보기
6/9

AWS의 최고의 장점은 사용 안하는 리소스에 대해 Off를 자유롭게 할수 있다는 점 아닐까. 돈을 아낄 수 있다.
업무시간 외에 사용량이 없는 EC2를 모두 꺼버리자.
EC2 목록에 있는 모든 인스턴스를 off 시키는것이니 운영 상황에서는 되도록 쓰지 말자!

1. Lambda 생성

Tag가 없어도 EC2를 강제로 중지시킬 수 있는 Lambda 함수를 알아보자.
EC2 인스턴스 목록에 있는 모든 EC2를 중지시킨다.

import boto3

region = 'ap-northeast-2'
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    response = ec2.describe_instances()
    
    all_instance_ids = []
    for reservation in response['Reservations']:
        for instance in reservation['Instances']:
            all_instance_ids.append(instance['InstanceId'])
    
    if all_instance_ids:
        ec2.stop_instances(InstanceIds=all_instance_ids)
        print('Stopped all EC2 instances:', all_instance_ids)
    else:
        print('No EC2 instances found in the region:', region)

ap-northeast-2 (서울) 리전에 있는 EC2 인스턴스의 정보를 가져와 모든 EC2를 중지시킨다.
EventBridge와 함께 사용해 사용하지 않는 시간에는 모두 꺼버리자!

profile
AWS 운영기록 💾

0개의 댓글