newdwh2021/lambda/stop-rds/stop-rds.py
2022-11-08 16:24:12 +09:00

27 lines
1.2 KiB
Python

import boto3
import os
#環境変数
client = boto3.client('rds')
AUTO_STOP_TAG_TAGKEY = os.environ['AUTO_STOP_TAG_TAGKEY']
AUTO_STOP_ENABLE = os.environ['AUTO_STOP_ENABLE']
def lambda_handler(event, context):
#クラスターを停止
clusters = client.describe_db_clusters()
for cluster in clusters['DBClusters']:
if cluster['Status'] == "available":
tags = client.list_tags_for_resource(ResourceName=cluster['DBClusterArn'])
for tag in tags['TagList']:
if tag['Key'] == AUTO_STOP_TAG_TAGKEY and tag['Value'] == AUTO_STOP_ENABLE:
client.stop_db_cluster(DBClusterIdentifier=cluster['DBClusterIdentifier'])
#インスタンスを停止
instances = client.describe_db_instances()
for instance in instances['DBInstances']:
if instance['DBInstanceStatus'] == "available":
tags = client.list_tags_for_resource(ResourceName=instance['DBInstanceArn'])
for tag in tags['TagList']:
if tag['Key'] == AUTO_STOP_TAG_TAGKEY and tag['Value'] == AUTO_STOP_ENABLE:
client.stop_db_instance(DBInstanceIdentifier=instance['DBInstanceIdentifier'])