Created
September 2, 2020 01:20
-
-
Save wesleymonaro/558eadb3d028b435995997070608dfed to your computer and use it in GitHub Desktop.
rds_stop_business_hours.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
import sys, traceback | |
from datetime import datetime | |
from time import sleep | |
def stop_rds_instances(): | |
start_time = datetime.now() | |
# starting ec2 client for list regions | |
ec2_client = boto3.client('ec2') | |
# starting rds client | |
rds_client = boto3.client('rds') | |
regions = ec2_client.describe_regions() | |
for region in regions['Regions']: | |
try: | |
print("Region: " + str(region['RegionName'])) | |
rds_client = boto3.client('rds', region_name=region['RegionName']) | |
instances = rds_client.describe_db_instances() | |
instanceIds = list() | |
for instance in instances['DBInstances']: | |
arn = instance['DBInstanceArn'] | |
if instance['DBInstanceStatus'] == "available": | |
tags = rds_client.list_tags_for_resource(ResourceName=arn)['TagList'] | |
for tag in tags: | |
try: | |
if tag['Key'] == 'working' and tag['Value'] == 'only-business-hours' : | |
print(tag) | |
instanceIds.append(instance['DBInstanceIdentifier']) | |
except: | |
print "Not expected error: ", traceback.print_exc() | |
if len(instanceIds) > 0 : | |
for instanceId in instanceIds: | |
print "Stopping RDS instance: " + str(instanceId) | |
rds_client.stop_db_instance(DBInstanceIdentifier=instanceId) | |
except: | |
print "Not expected error:", traceback.print_exc() | |
end_time = datetime.now() | |
took_time = end_time - start_time | |
print "Total time of execution: " + str(took_time) | |
def lambda_handler(event, context): | |
print('Stopping RDS instances... ') | |
stop_rds_instances() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment