Skip to content

Instantly share code, notes, and snippets.

@gmariette
Created May 18, 2020 09:00
Show Gist options
  • Select an option

  • Save gmariette/c1926d44492b0bf14281fb3b49fe775a to your computer and use it in GitHub Desktop.

Select an option

Save gmariette/c1926d44492b0bf14281fb3b49fe775a to your computer and use it in GitHub Desktop.
import os
import re
import sys
import boto3
import concurrent.futures
# Get the script action
action = str(sys.argv[1])
def describeInstances(action):
# Get all the instances
response = RDSclient.describe_db_instances()
allDB = response['DBInstances']
if action == "start":
# Filter on the one that are not running yet
rdsInstances = [x['DBInstanceIdentifier'] for x in allDB if x['DBInstanceStatus'] != 'available' and 'my-db-xxx' in x['DBInstanceIdentifier']]
return rdsInstances
if action == "stop":
# Filter on the one that are running
rdsInstances = [x['DBInstanceIdentifier'] for x in allDB if x['DBInstanceStatus'] == 'available' and 'my-db-xxx' + ENV_NAME_MIN in x['DBInstanceIdentifier']]
return rdsInstances
# Start rds instance based on it s name
def startRDSinstance(instanceidentifier):
try:
response = RDSclient.start_db_instance(
DBInstanceIdentifier=instanceidentifier
)
except:
return ("Cannot start " + instanceidentifier)
# Stop rds instance based on it s name
def stopRDSinstance(instanceidentifier):
try:
response = RDSclient.stop_db_instance(
DBInstanceIdentifier=instanceidentifier
)
except:
return ("Cannot stop " + instanceidentifier)
# Waiter until the instance is ready
def waitRDSInstanceAvailable(instanceidentifier):
waiter = RDSclient.get_waiter('db_instance_available')
waiter.wait(
DBInstanceIdentifier=instanceidentifier
)
# Main script
rdsInstances = describeInstances(action)
if len(rdsInstances) == 0:
print("All instances are already in a \"" + action + "\" state")
else:
print("Instances to " + action +" : " + str(rdsInstances))
if action == "start":
# Threading the start
for i in range(0, len(rdsInstances)):
with concurrent.futures.ThreadPoolExecutor() as executor:
threadStartRDS = executor.submit(startRDSinstance(rdsInstances[i]), i+1)
print("Starting " + rdsInstances[i])
# Threading the wait start
for j in range(0, len(rdsInstances)):
with concurrent.futures.ThreadPoolExecutor() as executor:
print("Waiting the good start of " + rdsInstances[i])
threadWaitRDS = executor.submit(waitRDSInstanceAvailable(rdsInstances[i]), i+1)
print("Instance " + rdsInstances[i] + " started")
elif action == "stop":
# Threading the stop
for i in range(0, len(rdsInstances)):
with concurrent.futures.ThreadPoolExecutor() as executor:
threadStartRDS = executor.submit(stopRDSinstance(rdsInstances[i]), i+1)
print("Stopping " + rdsInstances[i])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment