Skip to content

Instantly share code, notes, and snippets.

@meadhikari
Created June 14, 2015 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meadhikari/c528f28ad3973dd79320 to your computer and use it in GitHub Desktop.
Save meadhikari/c528f28ad3973dd79320 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
#Usage
#script.py -r <region name>(optional) -e <environment tagname> <action>[start|stop|status]
from optparse import OptionParser
import boto.ec2
def get_options():
global options
parser = OptionParser(usage="usage: %prog [options] start|stop|status", version="%prog 1.0")
parser.add_option("-r", "--region",
help="Region (default eu-west-1)",
dest="region",
default="eu-west-1")
parser.add_option("-e", "--environment",
help="Service (prod, dev, tmp or all)",
dest="environment",
default="tmp")
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("Error: You need to specify an action")
sys.exit(1)
else:
setattr(options, 'action', args[0])
return options
def main():
options = get_options()
action = options.action
environment_tag = options.environment
STOPPED = "stopped"
RUNNING = "running"
region = "eu-west-1"
aws_access_key_id = "<key>"
aws_secret_access_key="<key>"
conn = boto.ec2.connect_to_region(region,
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key)
no_found = True
reservations = conn.get_all_reservations()
for reservation in reservations:
for instance in reservation.instances:
if 'environment' in instance.tags:
if environment_tag in instance.tags['environment']:
no_found = False
if action == "start" and instance.state == STOPPED:
conn.start_instances(instance_ids=[instance.id])
print "starting "+instance.tags['Name']
elif action == "stop" and instance.state == RUNNING:
conn.stop_instances(instance_ids=[instance.id])
print "stopping "+instance.tags['Name']
elif action == "status":
print "The instance with instance name "+instance.tags['Name'] +" is currently "+instance.state
else:
print "Instance already "+ instance.state
if no_found:
print "No server found matching the tag"
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment