Skip to content

Instantly share code, notes, and snippets.

@chloegrace94
Created October 2, 2018 15:51
Show Gist options
  • Select an option

  • Save chloegrace94/3bccf08c5a758239210a76e9b993c612 to your computer and use it in GitHub Desktop.

Select an option

Save chloegrace94/3bccf08c5a758239210a76e9b993c612 to your computer and use it in GitHub Desktop.
Functions to stop and start RDS and EC2 instances
# Stop RDS instances
def stop_start_rds(session, inst_name, action, instance_id_or_arn):
try:
client = session.client('rds', region_name=region)
db_instances = client.describe_db_instances(DBInstanceIdentifier=inst_name)
# get the instance if it can be found
if len(db_instances) != 0:
db_instance = db_instances['DBInstances'][0]
else:
msg = ("Sorry!, I can't do that for you right now, I can't find instance *" + inst_name + "*")
return msg
raise Exception("Instance *" + inst_name + "* does not exist or is not currently launched")
curr_state = db_instance.get('DBInstanceStatus')
if (action.upper() == "STOP" and curr_state.upper() == 'AVAILABLE'):
client.stop_db_instance(DBInstanceIdentifier=inst_name)
msg = ":heavy_check_mark: *" + inst_name + "* successfuly stopping"
else:
msg = ('*RDS* instance *' + inst_name + '* is currently *'
+ curr_state
+ '*, no action needed at this time'
)
return msg #, response_type
except Exception as err:
logger.error('Error: %s' % str(err))
error_message = ("Sorry, the *RDS* instance *" + inst_name + "* does not exist or is not currently launched")
return error_message
# ----------------------------------------------------------------------------------------------------------------------
# # Stop EC2 instances
def stop_start_ec2(session, inst_name, action, instance_id_or_arn):
try:
ec2 = session.resource('ec2', region_name=region)
inst = ec2.Instance(id=instance_id_or_arn)
# Get current state
curr_state = inst.state['Name']
if (action.upper() == "STOP" and curr_state.upper() == 'RUNNING'):
inst.stop()
msg = ":heavy_check_mark: *" + inst_name + "* successfuly stopping"
else:
msg = ("*EC2* instance *" + inst_name + "* is currently *" + curr_state + "*, no action needed at this time")
return msg
except Exception as err:
logger.error('Error: %s' % str(err))
error_message = ("Sorry <@" + user + ">, the *EC2* instance *" + inst_name + "* cannot be found")
return error_message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment