FinOps

[Lambda] 업무시간 외 AuroraDB Stop/Start

김붕어87 2025. 4. 14. 13:57
반응형

개요
DEV환경은 업무시간에만 사용하는 테스트 환경입니다.
업무시간(09:00 ~ 18:00) 외 모든 리소스를 Stop하고 업무시간에는 모든 리소스를 Start 해서 요금을 줄입니다.

업무시간 : 09:00 ~ 18:00 (총 9시간)
업무시간 외 : 24시간 - 업무시간 (총 15시간) 

1DAY : 업무시간 외 Stop을 하면 하루에 15시간 요금을 줄일 수 있습니다.
365DAY : 15 * 365 = 5475시간 ( 5475시간 / 24시간 = 228.125일)
1년 기준으로 하면 228일 요금을 줄일 수 있습니다.

 

 

1. 요금을 줄일 수 있는 리소스

  • EC2
  • RDS DB
  • WorkerNode
  • Fargate 

 

2. 요금을 줄이는 스케쥴링 방식

Stop & Start 스케쥴링은 여러 방식이 있습니다.

이 글에서는 Lambda + EventBrige 방식으로 진행합니다.

 

ex)

EventBridge Rule : 09:00시 -> Start AuroraDB Lambda 실행

EventBridge Rule : 18:00시 -> Stop AuroraDB instance Lambda 실행

 

 

 

 

3. AuroraDB 스케쥴링

 

3-1. IAM Role 생성 

[ Lambda에서 사용할 Role Policy 생성 ]

Lambda 함수에서 AuroraDB Stop & Start 권한 넣기

 

AWS Consoel -> IAM -> Policy -> policy 생성

Policy Name : dev-lambda-aurora-Policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "rds:StartDBCluster",
                "rds:StopDBCluster",
                "rds:ListTagsForResource",
                "rds:DescribeDBInstances",
                "rds:StopDBInstance",
                "rds:DescribeDBClusters",
                "rds:StartDBInstance",
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeSubnets",
                "ec2:DescribeVpcs"
            ],
            "Resource": "*"
        }
    ]
}

 

 

AWS Consoel -> IAM -> Role -> Role 생성

Role Name : dev-lambda-schedule-role

Policy Attach : dev-lambda-aurora-Policy

 

 

[ EventBridge에서 사용할 Role & Policy 생성 ]

EventBridge에서 Lambda 함수를 실행할 권한 넣기

AWS Consoel -> IAM -> Policy -> policy 생성

Policy Name : dev-Amazon-EventBridge-Scheduler-Execution-Policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "lambda:InvokeFunction"
            ],
            "Resource": [
                "arn:aws:lambda:ap-northeast-2:xxx:function:StopAuroraDB:*",
                "arn:aws:lambda:ap-northeast-2:xxx:function:StopAuroraDB",
                "arn:aws:lambda:ap-northeast-2:xxx:function:StartAuroraDB:*",
                "arn:aws:lambda:ap-northeast-2:xxx:function:StartAuroraDB"
            ]
        }
    ]
}

 

AWS Consoel -> IAM -> Role -> Role 생성

Role Name : dev-Amazon_EventBridge_Scheduler_LAMBDA_role

Policy Attach : dev-Amazon-EventBridge-Scheduler-Execution-Policy

 

 

3-2. Lambda 함수 생성 

 

  • StopAuroraDB Lambda 함수 만들기

AWS Console -> Lambda -> 함수 -> 함수 생성 

함수 이름 : StopAuroraDB

런타임 : Python 3.9

기본 실행 역할 변경 -> 실행 역할 : 기존 역할 사용 클릭

기존 역할 : dev-lambda-schedule-role 클릭

함수 생성 

 

코드 소스

import boto3
import os

def lambda_handler(event, context):
    region = os.environ.get('AWS_REGION', 'ap-northeast-2')
    db_cluster_identifier = 'dev-db'  # 여기에 Aurora 클러스터 이름을 하드코딩하세요.

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

    try:
        response = rds.stop_db_cluster(DBClusterIdentifier=db_cluster_identifier)
        print(f'Successfully stopped Aurora PostgreSQL Compatible cluster: {db_cluster_identifier}')
        return {
            'statusCode': 200,
            'body': f'Successfully stopped Aurora PostgreSQL Compatible cluster: {db_cluster_identifier}'
        }
    except Exception as e:
        print(f'Error stopping Aurora PostgreSQL Compatible cluster {db_cluster_identifier}: {e}')
        return {
            'statusCode': 500,
            'body': f'Error stopping Aurora PostgreSQL Compatible cluster: {e}'
        }

 

 

Deploy 코스 업로드

TEST 실행 

 

AWS -> AWS CloudTrail -> 이벤트 기록  클릭

속성 조회 : 이벤트 이름

값 : StopDBCluster

Lambda가 AuroraDB stop되었는지 감사로그 확인 가능

 

  • StartAuroraDB Lambda 함수 만들기

AWS Console -> Lambda -> 함수 -> 함수 생성 

함수 이름 : StartAuroraDB

런타임 : Python 3.9

기본 실행 역할 변경 -> 실행 역할 : 기존 역할 사용 클릭

기존 역할 : dev-lambda-schedule-role 클릭

함수 생성 

 

코드 소스

import boto3
import os

def lambda_handler(event, context):
    region = os.environ.get('AWS_REGION', 'ap-northeast-2')
    db_cluster_identifier = 'dev-db'

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

    try:
        response = rds.start_db_cluster(DBClusterIdentifier=db_cluster_identifier)
        print(f'Successfully started Aurora PostgreSQL Compatible cluster: {db_cluster_identifier}')
        return {
            'statusCode': 200,
            'body': f'Successfully started Aurora PostgreSQL Compatible cluster: {db_cluster_identifier}'
        }
    except Exception as e:
        print(f'Error starting Aurora PostgreSQL Compatible cluster {db_cluster_identifier}: {e}')
        return {
            'statusCode': 500,
            'body': f'Error starting Aurora PostgreSQL Compatible cluster: {e}'
        }

 

Deploy 코스 업로드

TEST 실행 

 

 

 

 

3-1. EventBridge 생성 

AWS Console -> Amazon EventBridge -> 일정 -> 일정 생성 

일정 이름 : StopAuroraDB

설명 : Scheduling server off outside of business hours

일정 그룹 : 선택

일정 패턴 : 반복 일정 선택

시간대 : (UTC+09:00) Asia/Seoul)

일정 유형 : Cron 기반 일정

Cron 표현식 : 0 18 ? * MON-FRI *

유연한 기간 : 꺼짐

 

대상 세부 정보 : AWS Lambda 선택

Lambda 함수 : StopAuroraDB 선택 

 

일정 완료 후 작업 : NONE

재시도 정책 : No

DLQ : 없음

 

기존 역할 사용 : dev-Amazon_EventBridge_Scheduler_LAMBDA_role 선택

 

 

 

 

 

 

 

 

 

 

반응형

'FinOps' 카테고리의 다른 글

[Lambda] awscli Layer 설정  (0) 2025.04.16
[Lambda] 업무시간 외 Fargate Stop/Start  (0) 2025.04.16
[Lambda] 업무시간 외 EC2 Stop/Start  (0) 2025.04.14