Skip to content

Instantly share code, notes, and snippets.

@kristianperkins
Last active April 26, 2019 04:37
Show Gist options
  • Save kristianperkins/eb2a0e6dbcaede5cd7f340d2ddcedca1 to your computer and use it in GitHub Desktop.
Save kristianperkins/eb2a0e6dbcaede5cd7f340d2ddcedca1 to your computer and use it in GitHub Desktop.
Stop all EC2 instances with the 'Stoppable': 'true' tag
#!/usr/bin/env python3
import boto3
s = boto3.Session(profile_name='profile')
ec2 = s.resource('ec2')
instances_to_stop_filter = [
{ 'Name':'tag:Stoppable', 'Values': ['true'] },
{ 'Name':'instance-state-name', 'Values': ['running'] }
]
instances = ec2.instances.filter(Filters=instances_to_stop_filter)
print('stopping instances')
for inst in instances:
tags = {tag['Key']: tag['Value'] for tag in inst.tags}
print('stopping', inst.id, tags.get('Name', '<unknown>'))
ec2.instances.filter(InstanceIds=[i.id for i in instances]).stop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment