AWS/Project

Lambda를 활용한 EC2 자동 중지(stop)

jih0ssang 2023. 10. 28. 16:25

다음은 Lambda를 활용해 태그 기반 특정 시간대에 EC2 인스턴스 자동 중지(STOP) 되도록 Cron 작업을 수행하도록 할 예정이다.

 

작성중

10/28  SCP에 MFA 인증이 걸려있어서 Lambda 작동 안함

→ SCP MFA 인증 제한 일부 수정하여 해결

 

IAM > Policy 생성

Policy "LambdaSchedule"을 생성한다.

JSON 형식으로 작성한다.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ec2:Describe*",
            "Resource": "*"
        },
        {
            "Side": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ec2:Describe*",
                "ec2:Start*",
                "ec2:Stop*"
            ],
            "Resource": [
                "*"
            ]
         }
     ]
 }

EC2에 대한 접근 권한을 부여하는 Policy이다.

 

IAM > Role 생성

Lambda > 함수 생성

Python으로 코드를 작성할 예정이므로 런타임은 Python 3.8을 선택해야 한다.

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'] == 'AutoShutDown':
        	instances.append(instance.id)
            
def lambda_handler(event, context):
	ec2.stop_instances(InstanceIds=instances)
    print('stopped your instances: ' + str(instances))

다음과 같이, 코드를 작성하고 Deploy한다.

EC2 생성 시 걸었던 태그 Key 값이  "AutoShutDown"이 있다면 Stop하라는 내용이다.

 

Amazon EventBridge Scheduler > 일정 생성

규칙 생성으로 이동하면 UTC 시간(+8 hour)에 맞춰서 시간 작성해야하는 번거로움이 있다.

EventBridge SchedulerUTC 시간에 상관없이 내 시간대(Asia/Seoul)에 맞춰 작성해도 되는 편리함이 있다.

그래서 Scheduler > 일정에서 일정을 생성했다.

Schedule 생성 완료했다.

 

AWS Organizations > SCP 생성

다음은 생성한 Lambda를 Organizations 멤버 계정들에게도 적용하기 위해 SCP를 생성할 것이다.

 

근데 SCP는 Deny 하기 위한 Policy라서 "Effect": "Allow" 쓰려면 "Resource": "*" 써야한다고 함.

그래서 다 Deny하고 일부만 제외 하는 문법을 써서 Allow 를 쓰라는데....

일단 자고 일어나서 이어서...