ABOUT ME

Today
Yesterday
Total
  • Lambda를 이용한 EC2 시작/중지 자동화
    AWS/Lambda 2022. 8. 11. 17:50

    [목표]

    지정한 시간에 CloudWatch 이벤트를 발생시켜 Lambda를 호출하고, Lambda가 EC2 Instance를 제어(Start, Stop)

     

    1.    Lambda를 위한 IAM 정책 생성

     

    {

        "Version": "2012-10-17",

        "Statement": [

            {

                "Sid": "VisualEditor0",

                "Effect": "Allow",

                "Action": [

                    "ec2:StartInstances",

                    "ec2:StopInstances"

                ],

                "Resource": "arn:aws:ec2:*:*:instance/*"

            },

            {

                "Sid": "VisualEditor1",

                "Effect": "Allow",

                "Action": "ec2:DescribeInstances",

                "Resource": "*"

            }

        ]

    }

     

    2. Lambda를 위한 IAM Role 생성

     

    - IAM 정책을 생성하여 Role을 생성

     

    3. Lambda(EC2 Start) 함수 생성

     

    - 전에 생성한 역할을 선택하여 생성

    - Region 확인하고 실행하고자 하는 Instance ID 넣어줍니다. 2 이상일 경우 , 구분하여 넣어줍니다.

     

    Python 2.7 (더 이상 Lambda가 Python 2.7을 지원하지 않는다.)

     

    import boto3

    region = 'ap-northeast-2'

    instances = ['your-instance-id']

     

    def lambda_handler(event, context):

        ec2 = boto3.client('ec2', region_name=region)

        ec2.start_instances(InstanceIds=instances)

        print 'started your instances: ' + str(instances)

     

    Python 3.9

     

    import boto3
    region = 'ap-northeast-2'
    instances = ['your-instance-id', ''your-instance-id-2']
    ec2 = boto3.client('ec2', region_name=region)

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

     

    4. Lambda(EC2 Stop) 함수 생성

    - 동일하게 구성하되, Start 부분을 Stop으로 변경

     

    Python 2.7 (더 이상 Lambda가 Python 2.7을 지원하지 않는다.)

     

    import boto3

    region = 'ap-northeast-2'

    instances = ['your-instance-id']

     

    def lambda_handler(event, context):

        ec2 = boto3.client('ec2', region_name=region)

        ec2.stop_instances(InstanceIds=instances)

        print 'stopped your instances: ' + str(instances)

     

    Python 3.9

     

    import boto3
    region = 'ap-northeast-2'
    instances = ['your-instance-id', ''your-instance-id-2']
    ec2 = boto3.client('ec2', region_name=region)

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

     

    5. Lambda 함수를 트리거하는 CloudWatch 규칙 생성 

    - Instance Start 시간 규칙 생성

    - ex) ~ 09:00 시작일 경우 Cron표현식 (00 00 ? * MON-FRI *) GMT시간 +  9시간 = 한국 시간

    - Instance 실행시키는 Lambda 함수를 선택합니다.

     

    6. 두번째로 위와 같은 방식으로 Instance Stop시킬 규칙을 생성

    - 지정한 시간에 Lambda 함수가 실행되어 Instance Stop

     

    7. 시간에 맞춰서 실행되는 Instance

    - Lambda 실행되어 지정한 Instance 실행됨

     

    8. SNS 추가

    - 대상 추가를 통해 CloudWatch 이벤트 발생 Lambda 호출을 하면서 SNS알림도 호출할 수 있습니다.

     

    !실행오류 발생시!

     

    람다함수 실행을 위한 제한시간 수정

     

    [참고]

     

    https://aws.amazon.com/ko/premiumsupport/knowledge-center/start-stop-lambda-eventbridge/

     

    Lambda를 사용하여 EC2 인스턴스를 설정 간격으로 중지 및 시작하기

    EC2 인스턴스를 자동으로 중지 및 시작하여 Amazon Elastic Compute Cloud(Amazon EC2) 사용량을 줄이려고 합니다. 이를 위해 AWS Lambda 및 Amazon EventBridge를 사용하려면 어떻게 해야 하나요? 중요: 리전에서 ‘us

    aws.amazon.com

    댓글

Designed by Tistory.