Skip to content

Instantly share code, notes, and snippets.

@espozbob
Forked from tomislacker/ec2_kill_with_fire.py
Created November 14, 2018 06:32
Show Gist options
  • Save espozbob/ce27432e0f1c3e45642d8dea70f05d36 to your computer and use it in GitHub Desktop.
Save espozbob/ce27432e0f1c3e45642d8dea70f05d36 to your computer and use it in GitHub Desktop.
Kill EC2 Instances With Fire
#!/usr/bin/env python
"""
EC2 Instance Killer
Usage:
ec2_kill_with_fire.py [options] <instance_id>...
Options:
-h, --help Show this dialog
-r, --region NAME EC2 region [default: us-east-1]
-l, --log-level NAME Python logging level [default: info]
"""
from __future__ import print_function
import boto3
import logging
log = logging.getLogger(__name__)
def disable_termination_protection(instance):
has_protection = instance.describe_attribute(
Attribute='disableApiTermination'
)['DisableApiTermination']['Value']
if not has_protection:
log.debug("No termination protection on {iid}".format(
iid=instance.id,
))
else:
log.info("Disabling termination protection on {iid}".format(
iid=instance.id,
))
instance.modify_attribute(
DisableApiTermination={'Value': False},
)
def kill_instance_with_fire(instance):
# Ensure no instance protection is enabled
disable_termination_protection(instance)
# Determine EBS block devices to delete after instance termination
ebs_to_delete = [
d['Ebs']['VolumeId']
for d in instance.block_device_mappings
if 'Ebs' in d and not d['Ebs']['DeleteOnTermination']
]
if any(ebs_to_delete):
log.warning("Deleting {vols} volumes after termination...".format(
vols=len(ebs_to_delete),
))
log.info("Deleting volumes: {vols}".format(
vols=", ".join(ebs_to_delete)),
)
# Terminate the instance
log.warning("Terminating instance: {iid}".format(
iid=instance.id),
)
instance.terminate()
# Wait for the instance to terminate
instance.wait_until_terminated()
# Delete remaining EBS volumes
ec2_client = instance.meta.client
for vol_id in ebs_to_delete:
log.info("Deleting volume: {vid}".format(
vid=vol_id,
))
ec2_client.delete_volume(VolumeId=vol_id)
if __name__ == '__main__':
import sys
from docopt import docopt
args = docopt(__doc__, version='EC2 Kill With Fire v0.0.1')
logging.basicConfig(**{
'level': getattr(logging, args['--log-level'].upper()),
'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
})
ec2 = boto3.resource('ec2', region_name=args['--region'])
if not any(args['<instance_id>']):
log.critical("No instance Ids provided")
sys.exit(1)
for instance_id in args['<instance_id>']:
kill_instance_with_fire(ec2.Instance(instance_id))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment