I think I've rewritten this code 3 times now in the last year so it seems prudent to save it somewhere.  If other folks find it useful that'd be great.

The problem is a simple one.  You're looking to setup and install of a few machines on EC2, perhaps to run something fun like a Cassandra cluster.

Typically it's really tempting to just setup the security group once and never ever touch it again.  I'd log into the the AWS console, and following along with this datastax guide I would manually setup the group, launch instances, etc.

However, without automation there's some duplication of effort whenever someone on your team sets up a cluster and possibility for user error setting up security groups.  And of course we're already automating the other important bits like "launch a new instance" or "run a backup" already so why not manage security groups with the same scripts?

I'm currently working with Fabric to automate EC2 stuff so I pulled out the Python code I'm using to handle creation of security groups and permission rules within those groups.

The script attempts to be idempotent.  The idea here is that simply rerunning the script will, only if necessary, create groups, revoke old rules and authorize any new ones.

Anyway, without further ado here's the script: