Skip to content

Instantly share code, notes, and snippets.

@seventhskye
Created August 1, 2016 10:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save seventhskye/406e7e722b9792bc18a47844878b9e60 to your computer and use it in GitHub Desktop.
Save seventhskye/406e7e722b9792bc18a47844878b9e60 to your computer and use it in GitHub Desktop.
A python script to shutdown amazon instances, and autoscaling groups. Requires a tag called ScheduledUptime=True on resources this script need to apply to.
#!/usr/bin/env python
import sys
import boto3
def main(argv):
ec2 = boto3.resource('ec2')
instances = ec2.instances.all()
elb = boto3.client('elb')
autoscaling = boto3.client('autoscaling')
auto_scaling_groups = autoscaling.describe_auto_scaling_groups()['AutoScalingGroups']
scheduled=[]
if len(sys.argv) > 1 and argv[1] == 'on':
for i in instances:
if i.state['Name'] == 'stopped':
for t in i.tags:
if t['Key'] == 'ScheduledUptime':
if t['Value'] == 'True':
response = ec2.Instance(i.id).start()
print ' --> Starting Instance {}'.format(i.id)
scheduled.append(i)
break
for i in scheduled:
for t in i.tags:
if t['Key'] == 'ElasticLoadbalancerName':
response = elb.register_instances_with_load_balancer(LoadBalancerName=t['Value'],Instances=[{'InstanceId': i.id}])
print " --> Registering instance {}".format(t['Value'])
break
for asg in auto_scaling_groups:
for t in asg['Tags']:
if t['Key'] == 'ScheduledUptime':
if t['Value'] == 'True':
if asg['DesiredCapacity'] < 1:
print " --> Scaling up AutoScaling Group {}".format(asg['AutoScalingGroupName'])
response = autoscaling.update_auto_scaling_group(AutoScalingGroupName=asg['AutoScalingGroupName'],DesiredCapacity=2,MinSize=0)
break
elif len(sys.argv) > 1 and argv[1] == 'out':
for i in instances:
if i.state['Name'] == 'running':
for t in i.tags:
if t['Key'] == 'ScheduledUptime':
if t['Value'] == 'True':
response = ec2.Instance(i.id).stop()
print ' --> Stopping Instance {}'.format(i.id)
scheduled.append(i)
break
for i in scheduled:
for t in i.tags:
if t['Key'] == 'ElasticLoadbalancerName':
response = elb.deregister_instances_from_load_balancer(LoadBalancerName=t['Value'],Instances=[{'InstanceId': i.id}])
print ' --> Deregistering Instance from load-balancer {}'.format(LoadBalancerName['Value'])
break
for asg in auto_scaling_groups:
for t in asg['Tags']:
if t['Key'] == 'ScheduledUptime':
if t['Value'] == 'True':
if asg['DesiredCapacity'] > 0:
print " --> Scaling down AutoScaling Group {}".format(asg['AutoScalingGroupName'])
response = autoscaling.update_auto_scaling_group(AutoScalingGroupName=asg['AutoScalingGroupName'],DesiredCapacity=0,MinSize=0)
break
else:
print "Usage: lights on|out"
if __name__ == "__main__":
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment