Skip to content

Instantly share code, notes, and snippets.

@AdrienLemaire
Created October 19, 2011 03:50
Show Gist options
  • Save AdrienLemaire/1297437 to your computer and use it in GitHub Desktop.
Save AdrienLemaire/1297437 to your computer and use it in GitHub Desktop.
Boto script
def restart_server(server_name=None):
"""Restart the server if needed (e.g. server down due to abusive cpu usage
by a program
how to use::
$ fab restart_server:serverName
List of available servers names:
- git
- test
- live
.. note:: You need to define both AWS_ACCESS_KEY_ID and
AWS_SECRET_ACCESS_KEY in your fab_settings file
"""
import boto
from boto.exception import EC2ResponseError
if not server_name:
print("No server name specified, default to 'git' server")
server_name = "git"
if server_name == "live":
# Be prudent when restarting the live server
if not confirm("Are you sure you want to restart the production "\
"server?", default=False):
return
# get id associated to the name
server_name, server_region = {
"git": ["MGMT01", "ap-southeast-1"],
"test": ["Test-Django-01", "ap-northeast-1"],
"live": ["Prod-Django-01", "ap-northeast-1"],
}[server_name]
credentials = {
"aws_access_key_id": local_settings.AWS_ACCESS_KEY_ID,
"aws_secret_access_key": local_settings.AWS_SECRET_ACCESS_KEY,
}
# Connect to ec2 (otherwise, regions are not availables)
boto.connect_ec2(**credentials)
# go to our region
regions = boto.ec2.regions(**credentials)
japan = [r for r in regions if r.name == server_region][0]
# connect to the region
conn_jap = japan.connect(**credentials)
# get instance id and ip through a tag
jap_tags = conn_jap.get_all_tags()
server_ip, server_id = [(tag.value, str(tag.res_id)) for tag in jap_tags
if tag.name == server_name][0]
conn_jap.stop_instances(server_id)
while 1:
try:
conn_jap.start_instances(server_id)
# the server is restarted, we now need to associate the instance
# with its elastic ip
conn_jap.associate_address(server_id, server_ip)
print("The server '%s' has been restarted" % server_id)
return
except EC2ResponseError:
# The instance is not in a state from which it can be started
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment