Saturday, 13 September 2014

AWS script of the day: Cascade delete of security groups

A common bug bear of AWS security groups is having to delete all references to a security group before deleting the group itself. Here is a quick boto script to simplify this process, you will need to have configured boto as per these instructions. After which 'python sg_cascade_delete -h' will give you:

usage: [-h] [--region REGION] [--quick] [--force]
                            group_ids [group_ids ...]

Remove all references to a security group and then delete it

positional arguments:
  group_ids        The ID of the security group to delete, eg. sg-xxxxxxx

optional arguments:
  -h, --help       show this help message and exit
  --region REGION  AWS region name the security group is in, default: us-
  --quick          Skip checks for whether or not the group is used by
                   RDS/ElastiCache. Faster but may cause error on delete if
                   the group is referenced.
  --force          Force delete without requiring confirmation
  --quiet          Do not print references or success message

An example of usage would be:
python sg_cascade_delete --region eu-west-1 sg-1231234

This will find all references to the sg-1231234 security group in the region and display them before asking for confirmation to delete the group. Note that you will be prevented from deleting any groups used in ElastiCache or RDS security groups as doing so tends to break things in unexpected ways.

If you don't want to have to confirm the deletion (for a large number of groups for example) you can specify the --force option, this will skip the confirmation question and simply delete the groups after displaying their references. For example:
python sg_cascade_delete --force --region eu-west-1 sg-1231234 sg-33221133

If you prefer your deletion silent then the --quiet option is for you, specifying this will prevent any messages being printed (other than the confirmation question and errors that occur). For no interaction at all use with --force to magically delete the groups without a sound. A non-zero process exit code indicates an error.

If you have a large number of ElastiCache clusters and RDS instances you can skip the reference checks by specifying the --quick  option, this may result in errors (in VPC) if the group is actually referenced when trying to delete and will cause some strange behaviour in EC2 classic as you are actually able to delete the group leaving a dangling authorisation on the ElastiCache/RDS security group. As such it is advised that you use this option with care or when you are truly certain that the security group is not used anywhere but in EC2.

As this code is mutating (it changes your stuff) it would be wise to run it in a test environment before making changes in production. In other words: use at your own risk.