Skip to content

Instantly share code, notes, and snippets.

@hoangvx
Created August 29, 2018 00:34
Show Gist options
  • Save hoangvx/a5769ef567e74541e54e27c91758c597 to your computer and use it in GitHub Desktop.
Save hoangvx/a5769ef567e74541e54e27c91758c597 to your computer and use it in GitHub Desktop.
Create a lambda function for auto start and stop rds instance by add tags into instance. Then, schedule it by cloudwatch event
import boto3
import time
# Example RDS Instance tags:
#
# Scheduled : True
# ScheduleStart : 06:00
# ScheduleStop : 18:00
##
#define boto3 the connection
rds = boto3.client('rds')
def lambda_handler(event, context):
print "Check RDS's tags"
# Get current time in format H:M
current_time = time.strftime("%H:%M")
# Search all the instances which contains scheduled filter
instances = rds.describe_db_instances()
stopInstances = []
startInstances = []
# Locate all instances that are tagged to start or stop.
for instance in instances["DBInstances"]:
tags = rds.list_tags_for_resource(ResourceName=instance["DBInstanceArn"])
for tag in tags["TagList"]:
if tag['Key'] == 'ScheduleStop':
if tag['Value'] == current_time:
stopInstances.append(instance["DBInstanceIdentifier"])
rds.stop_db_instance(DBInstanceIdentifier=instance["DBInstanceIdentifier"])
pass
pass
if tag['Key'] == 'ScheduleStart':
if tag['Value'] == current_time:
startInstances.append(instance["DBInstanceIdentifier"])
rds.start_db_instance(DBInstanceIdentifier=instance["DBInstanceIdentifier"])
pass
pass
pass
pass
print current_time
# shut down all instances tagged to stop.
if len(stopInstances) > 0:
# perform the shutdown
print stopInstances
else:
print "No rds instances to shutdown."
# start instances tagged to stop.
if len(startInstances) > 0:
# perform the start
print startInstances
else:
print "No rds instances to start."
@Developer-AWS
Copy link

Thanks!

@nitya1402
Copy link

nitya1402 commented Apr 29, 2020

Hi @hoangvx,

I am trying a similar code. I need to list the tags associated with an RDS instance. Below is my code and the error noticed. Please help.

Code:

def iterating_values_rds(i,name):
tags = rds.list_tags_for_resource(ResourceName=i["DBInstanceArn"])
for tag in tags["TagList"]:
try:
if(tag["Key"] == name):
print(str(i.id) + " Value exists " + name)
return tag["Value"]
except Exception as e:
pass
return ""

rds_instances = rds.describe_db_instances()
for i in rds_instances["DBInstances"]:
tags = rds.list_tags_for_resource(ResourceName=i["DBInstanceArn"])
    if tags["TagList"]:
        iapp = iterating_values_rds(i,"ApplicationName")

Expected output -= value of iapp.
Output Obtained:

Please help in fetching the user added tags(for example : "ApplicationName": "xyz").

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment