BESPIN Tech Blog
  • Home
  • Tech
    • CSP

      AWS

      GCP

      NCP

      Cloud

      Migration

      LZ, Control Tower

      Backup

      Monitoring

      Container

      Infra

      OS

      Middleware

      Data

      RDB

      Big Data Platform

      Application

      CI/CD

      BESPICK 구독하기 ㅣ 1668-1280

  • Trend
  • IT
최신 리포트 다운로드 지금 바로 문의하기
BESPIN Tech Blog
  • Home
  • Tech
    • CSP

      AWS

      GCP

      NCP

      Cloud

      Migration

      LZ, Control Tower

      Backup

      Monitoring

      Container

      Infra

      OS

      Middleware

      Data

      RDB

      Big Data Platform

      Application

      CI/CD

      BESPICK 구독하기 ㅣ 1668-1280

  • Trend
  • IT
최신 리포트 다운로드 지금 바로 문의하기
BESPIN Tech Blog
BESPIN Tech Blog
  • Tech
    • CSP
      • AWS
      • GCP
      • NCP
    • Cloud
      • Migration
      • LZ, Control Tower
      • Backup
      • Monitoring
      • Container
    • Infra
      • OS
      • Middleware
    • Data
      • RDB
      • Big Data Platform
    • Application
      • CI/CD
  • Trend
  • IT
  • Contact US
TECHCSPAWS

AWS 인스턴스 시작&중지(Lambda&EventBridge)

by 현지 박 2023년 03월 16일
2023년 03월 16일
5

안녕하세요~!

오늘은 베스핀글로벌 D&A실 김한종님이 작성해 주신 AWS 인스턴스 시작&중지(Lambda&EventBridge) 구축 가이드에 대해서 알아보겠습니다 🙂

1. 인스턴스 스케줄러 아키텍쳐

참조 URL : https://1mini2.tistory.com/67

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 식 이로 일정 선택

https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html

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

관련

LambdaEventBridgeAWS인스턴스람다IAM역할람다함수생성EC2태그지정이벤트브릿지

HOT Trend

Recent Posts

  • 딜로이트도, 맥킨지도, 베스핀글로벌도: AI 에이전트로 일 바꾸는 시대

    2025년 07월 04일 클라우드베스핀글로벌clouddata데이터AI인공지능HelpNow AIbespinglobalAI에이전트helpnow업무자동화딜로이트
  • ⚔️데이터센터에서 시작된 전쟁? 요즘 뜨는 AIDC 개념부터 트렌드까지!

    2025년 06월 27일 클라우드clouddata데이터AI데이터센터클라우드 데이터센터bespinglobalAIDCAI 인프라베스핀글로벌
  • 구글부터 엔비디아까지, 빅테크 기업들의 AI 전략 최신본📖

    2025년 06월 20일 cloud베스핀글로벌클라우드data데이터AI구글마이크로소프트엔비디아AI에이전트google I/ONVIDIA GTC 2025Microsoft build 2025
  • AI를 연결한다고? 업계가 주목하는 ‘MCP’ 알아보기🔍

    2025년 06월 13일 베스핀글로벌클라우드cloudAIMCP
  • [WhaTap] RDS Failover/Reboot 관제 2 – RDS Failover

    2025년 05월 30일 RDSRDS FailoverRebootFailoverbespin global

베스핀글로벌은 모든 기업의 AI 혁신을 실현하기 위해, 세상에서 가장 혁신적이고 자동화된 AI 서비스와 솔루션을 만들어갑니다.
상호 : 베스핀글로벌 주식회사 ㅣ 대표자명 : 김써니, 허양호 ㅣ 사업자등록증번호 : 638-87-00223 ㅣ 통신판매번호 : 2019-서울서초-0347 ㅣ 대표전화 : 1668-1280
사업장주소지 : 서울특별시 서초구 강남대로 327, 13,14,15,16층(서초동,대륭서초타워) ㅣ 이메일 : info@bespinglobal.com ㅣ 개인정보 처리방침 ㅣ 개인정보 처리방침 안내

© 2026 BESPIN GLOBAL, All Rights Reserved.

BESPINGLOBAL
패밀리 사이트
China MEA SEA US

BESPIN Tech Blog
  • Home
  • Tech
    • CSP

      AWS

      GCP

      NCP

      Cloud

      Migration

      LZ, Control Tower

      Backup

      Monitoring

      Container

      Infra

      OS

      Middleware

      Data

      RDB

      Big Data Platform

      Application

      CI/CD

      BESPICK 구독하기 ㅣ 1668-1280

  • Trend
  • IT