⭐️ Amazon Web Service

[Lambda] RDS 중지/ASG min값 0으로 수정

mini_world 2023. 2. 16. 23:02

특정 기간동안 사용하지 않을 RDS/ASG/EC2를 중지 시켜주는 스크립트 

stop-ec2-rds-during-vacation

import boto3
region = 'ap-northeast-2'
rds = boto3.client('rds')
asg = boto3.client('autoscaling')
ec2_r = boto3.resource('ec2')
ec2 = boto3.client('ec2', region_name=region)
instances = []


def lambda_handler(event, context):

    # RDS 인스턴스 중지
    dbs = rds.describe_db_instances()
    for db in dbs['DBInstances']:
        if (db['StorageType'] == 'gp2' or db['StorageType'] == 'gp3'):
            if (db['DBInstanceStatus'] == 'available'):
                DoNotStop=1
                try:
                    GetTags=rds.list_tags_for_resource(ResourceName=db['DBInstanceArn'])['TagList']
                    for tags in GetTags:
                        if(tags['Key'] == 'autostop' and tags['Value'] == 'true'):
                            result = rds.stop_db_instance(DBInstanceIdentifier=db['DBInstanceIdentifier'])
                            print ("{0}. RDS 인스턴스 중지".format(db['DBInstanceIdentifier']))
                    if(DoNotStop == 1):
                        DoNotStop=1
                except Exception as e:
                    print ("{0}. RDS 인스턴스 중지 실패".format(db['DBInstanceIdentifier']))
                    print(e)
        if (db['StorageType'] == 'aurora'):   
            if (db['DBInstanceStatus'] == 'available'):
                DoNotStop=1
                try:
                    GetTags=rds.list_tags_for_resource(ResourceName=db['DBInstanceArn'])['TagList']
                    for tags in GetTags:
                        if(tags['Key'] == 'autostop' and tags['Value'] == 'true'):
                            result = rds.stop_db_cluster(DBClusterIdentifier=db['DBClusterIdentifier'])
                            print ("{0}. RDS 인스턴스 중지".format(db['DBClusterIdentifier']))
                    if(DoNotStop == 1):
                        DoNotStop=1
                except Exception as e:
                    print ("{0}. RDS 인스턴스 중지 실패".format(db['DBClusterIdentifier']))
                    print(e)
    # ASG Min/Max사이즈 0으로 수정           
    asg_list = asg.describe_auto_scaling_groups()
    for asg_desc in asg_list['AutoScalingGroups']:
        try:
            result = asg.update_auto_scaling_group(
                AutoScalingGroupName=asg_desc['AutoScalingGroupName'],
                MinSize=0,
                MaxSize=0,)
            print(" {0}. 오토스케일링 그룹 min/max 0으로 수정 완료".format(asg_desc['AutoScalingGroupName']))
        except Exception as e:
            print ("{0}. 오토스케일링 min/max 0으로 수정 실패".format(asg_desc['AutoScalingGroupName']))
            print(e)
    # EC2 중지
    for instance in ec2_r.instances.all():
        for tag in instance.tags:
            if tag['Key'] == 'autostop':
                if tag['Value'] == 'true':
                    instances.append(instance.id)
    try:
        ec2.stop_instances(InstanceIds=instances)
        print("중지된 인스턴스 목록: " + str(instances))
    except Exception as e:
        print ("중지 실패 인스턴스 목록: " + str(instances))
        print(e)
                
                
if __name__ == "__main__":
    lambda_handler(None, None)