Created
July 29, 2016 08:54
-
-
Save nguyendangminh/70e5cf39986d7d9b384006d0332dfe42 to your computer and use it in GitHub Desktop.
Stop EC2 instances by tag
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Shameless copy from qwiklab | |
import boto.ec2, os | |
# Connect to EC2 in this region | |
region = os.environ.get('EC2_REGION') | |
connection = boto.ec2.connect_to_region(region) | |
# Get a list of all instances | |
reservations = connection.get_all_instances() | |
# Loop through each instance | |
for r in reservations: | |
for i in r.instances: | |
# Check for the 'stopinator' tag on running instances | |
if 'stopinator' in i.tags.keys(): | |
action = i.tags['stopinator'].lower() | |
# Stop? | |
if action == 'stop' and i.state == 'running': | |
print "Stopping instance", i.id | |
connection.stop_instances([i.id]) | |
# Terminate? | |
elif action == 'terminate' and i.state != 'terminated': | |
print "Terminating instance", i.id | |
connection.terminate_instances([i.id]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment