안녕하세요~!
오늘은 베스핀글로벌 D&A실 김한종님이 작성해 주신 AWS 인스턴스 시작&중지(Lambda&EventBridge) 구축 가이드에 대해서 알아보겠습니다 🙂
1. 인스턴스 스케줄러 아키텍쳐

2-1. 람다가사용할 IAM Role & Policy 설정

Lambda 에 적용할 정책 생성
2-2. 람다가사용할 IAM Role & Policy 설정

1. JSON 선택
2. 권한 기재
{
“Version”: “2012-10-17”,
“Statement”: [
{
“Sid”: “VisualEditor0”,
“Effect”: “Allow”,
“Action”: [
“ec2:Describe*”,
“ec2:Start*”,
“ec2:Stop*”,
“rds:StartDBCluster”,
“rds:StopDBCluster”,
“rds:ListTagsForResource”,
“rds:DescribeDBInstances”,
“rds:StopDBInstance”,
“rds:DescribeDBClusters”,
“rds:StartDBInstance”
],
“Resource”: “*”
}
] }
2-3. 람다가사용할 IAM Role & Policy 설정

1. Role 이름 및 설명 기재
2. 정책 생성
2-4. 람다가사용할 IAM Role & Policy 설정

Lambda 에 적용할 역할 생성
2-5. 람다가사용할 IAM Role & Policy 설정

1. AWS 서비스 선택
2. Lambda 선택
2-6. 람다가사용할 IAM Role & Policy 설정

미리 생성한 ec2-start-stop-role 선택

Lambda 에 적용할 Policy 이름 기재
3-1. 람다 함수 생성(Start Instance)

Lambda 에 적용할 역할 생성
3-2. 람다함수생성(Start Instance)

1. 함수 이름 : start-ec2-instance
2. 런타임 : Python 3.8
3. 기존 역할 : ec2-start-stop-lambda-policy
3-3. 람다함수생성(Start Instance)

1. EC2 Start 코드 작성
2. Region, Key 값, Value 값 설정
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’] == ‘auto-start’:
if tag[‘Value’] == ‘true’:
instances.append(instance.id)
def lambda_handler(event, context):
ec2.start_instances(InstanceIds=instances)
print(‘started your instances: ‘ + str(instances))
3-4. 람다함수생성(Start Instance/RDS 포함)
import boto3
instances = []
ec2 = boto3.resource(‘ec2’)
ec2_c = boto3.client(‘ec2’)
rds = boto3.client(‘rds’)
def lambda_handler(event, context):
#Start EC2 Instances
for instance in ec2.instances.all():
for tag in instance.tags:
if (tag[‘Key’] == ‘auto-start’ and tag[‘Value’] == ‘true’ and instance.state[‘Name’] == ‘stopped’):
instances.append(instance.id)
print(instances)
ec2_c.start_instances(InstanceIds=instances)
print(‘stopped your instances: ‘ + str(instances))
elif (tag[‘Key’] == ‘auto-start’ and tag[‘Value’] == ‘true’ and instance.state[‘Name’] == ‘running’):
print(‘All instances are started.’)
#Start DB Instances
dbs = rds.describe_db_instances()
for db in dbs[‘DBInstances’]:
#Check if DB instance stopped. Start it if eligible.
if (db[‘DBInstanceStatus’] == ‘stopped’):
doNotStart=1
try:
GetTags=rds.list_tags_for_resource(ResourceName=db[‘DBInstanceArn’])[‘TagList’]
for tags in GetTags:
#if tag “autostart=yes” is set for instance, start it
if(tags[‘Key’] == ‘auto-start’ and tags[‘Value’] == ‘true’):
result = rds.start_db_instance(DBInstanceIdentifier=db[‘DBInstanceIdentifier’])
print (“Starting instance: {0}.”.format(db[‘DBInstanceIdentifier’]))
if(doNotStart == 1):
doNotStart=1
except Exception as e:
print (“Cannot start instance {0}.”.format(db[‘DBInstanceIdentifier’]))
print(e)
else:
print(‘All RDS instances are started.’)
** 위 코드는 EC2 및 RDS 의 현재 상태(stopped/running) 를 파악하여 stopped 상태인 인스턴스만 구동시키는 코드입니다.
3-5. 람다함수생성(Start Instance)

Lambda 가동 시간 변경 시 편집하여 수동으로 수정
3-6. 람다함수생성(Start Instance)

기본으로 3초로 되어있어 30초로 수정

1. 기본 정보와 권한은 Start Instance 의 설정과 동일 하게 작성
2. EC2 Stop 코드 작성
3. Region, Key 값, Value 값 설정
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’] == ‘auto-stop’:
if tag[‘Value’] == ‘true’:
instances.append(instance.id)
def lambda_handler(event, context):
ec2.stop_instances(InstanceIds=instances)
print(‘stopped your instances: ‘ + str(instances))
3-7. 람다함수생성(Stop Instance/RDS 포함)
import boto3
instances = []
ec2 = boto3.resource(‘ec2’)
ec2_c = boto3.client(‘ec2’)
rds = boto3.client(‘rds’)
def lambda_handler(event, context):
#Stop EC2 Instances
for instance in ec2.instances.all():
for tag in instance.tags:
if (tag[‘Key’] == ‘auto-stop’ and tag[‘Value’] == ‘true’ and instance.state[‘Name’] == ‘running’):
instances.append(instance.id)
print(instances)
ec2_c.stop_instances(InstanceIds=instances)
print(‘stopped your instances: ‘ + str(instances))
elif (tag[‘Key’] == ‘auto-stop’ and tag[‘Value’] == ‘true’ and instance.state[‘Name’] == ‘stopped’):
print(‘All instances are stopped.’)
#Stop DB instances
dbs = rds.describe_db_instances()
for db in dbs[‘DBInstances’]:
#Check if DB instance is not already stopped
if (db[‘DBInstanceStatus’] == ‘available’):
DoNotStop=1
try:
GetTags=rds.list_tags_for_resource(ResourceName=db[‘DBInstanceArn’])[‘TagList’]
for tags in GetTags:
#if tag “autostop=yes” is set for instance, stop it
if(tags[‘Key’] == ‘auto-stop’ and tags[‘Value’] == ‘true’):
result = rds.stop_db_instance(DBInstanceIdentifier=db[‘DBInstanceIdentifier’])
print (“Stopping instance: {0}.”.format(db[‘DBInstanceIdentifier’]))
if(DoNotStop == 1):
DoNotStop=1
except Exception as e:
print (“Cannot stop instance {0}.”.format(db[‘DBInstanceIdentifier’]))
print(e)
else:
print(‘All RDS instances are stopped.’)
** 위 코드는 EC2 및 RDS 의 현재 상태(stopped/running) 를 파악하여 running 또는 available상태인 인스턴스만 구동시키는 코드입니다.
4. EC2 태그지정

1. EC2 에 2개의 태그 기재
2. auto-start : true 는 서버 부팅
3. auto-stop : true 는 서버 정지
5. Lambda 함수 정상 가동테스트
1. auto-start, auto-stop 함수에서 Test 클릭 시 서버 시작/정지 확인 이 가능
2. Test 처음 클릭 시 이벤트 이름만 추가하면 테스트 가능
6-1. Event Bridge(Start Event)

Event Bridge 에서 규칙 생성
6-2. Event Bridge(Start Event)

1. 규칙 이름 생성
2. 일정 선택
3. Cron 식 이로 일정 선택
https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html
4. 현재 시간대(GMT) 로 변경 하여 시간 확인
6-3. Event Bridge(Start Event)

1. 대상 에 Lambda 함수 선택
2. Lambda 함수 선택 – start-ec2-instance
6-4. Event Bridge(Stop Event)

1. 규칙 이름 생성
2. 일정 선택
3. Cron 식 이로 일정 선택
4. 현재 시간대(GMT) 로 변경 하여 시간 확인
6-5. Event Bridge(Stop Event)

1. 대상 에 Lambda 함수 선택
2. Lambda 함수 선택
– stop-ec2-instance
6-6. Event Bridge(Start / Stop Event)

Event Bridge 에 Start / Stop 2개의 규칙 생성 확인
감사합니다:)

문의: info@bespinglobal.com | 대표번호: 02-1688-1280