Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all security groups on Amazon ec2?

Tags:

amazon-ec2

I've created new EC2 spot requests over the last weeks. A new security group was created for every request. When the spot requests were deleted the security groups were not deleted. I've hit the 100 groups limit and want to delete them. The EC2 interface apparently allows only one deletion at a time, which means I would have to make 300 clicks to delete these groups. Or is there a better way to delete multiple security groups with few clicks or lines of code?

like image 366
Casady Avatar asked Dec 08 '13 02:12

Casady


2 Answers

THis would need some basic scripting and AWS SDK. you can do this with pretty much all the SDK provided by AWS.

I would prefer AWS-CLI as i already have it installed and configured. This is what I would do:

  1. list all the SGs with describe-security-groups
  2. Install jq (the Json parser for BASH)
  3. Pull the SG IDs (check this for jq syntax)
  4. Once you have the SG IDs, run delete-security-group by usig a for loop.

This is fairly simple and straight forward way of doing wat you want to do. THis can be done by any of the AWS SDKs.

These are just a couple of commands which can be constructed into a Bash script, provided:

  1. You have aws-cli installed and configured
  2. you have jq installed on your system.

If you already have some other AWS SDK installed, then you are better off with that as java/python/ruby...etc all have their own inbuilt way of parsing JSON/HASH/DataStructure.

Hope this helps.

like image 53
slayedbylucifer Avatar answered Nov 04 '22 05:11

slayedbylucifer


I think you can do this by combining a command that lists all security groups and one other that deletes them.

If you are using the python boto API (for example) that would be:

import boto
conn = boto.connect_ec2(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
groups = conn.get_all_security_groups() 

Which returns (as an example): [SecurityGroup:appserver, SecurityGroup:default, SecurityGroup:vnc, SecurityGroup:webserver]

And then you delete them all:

for group in groups:
    conn.delete_security_group(group.split(":")[1])

Edit

You should run the commands on your shell.

like image 26
Artem Tsikiridis Avatar answered Nov 04 '22 04:11

Artem Tsikiridis