Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A script that removes all non-default security group rules and groups in a single REGION using boto3
import boto3
from botocore.exceptions import ClientError
REGION = 'us-east-1'
ec2 = boto3.client('ec2', region_name=REGION)
# Keep removing until all are gone
while True:
groups = ec2.describe_security_groups()['SecurityGroups']
group_ids = [g['GroupId'] for g in groups]
groups_left = len(group_ids)
if groups_left > 0:
print(f'Groups left to deauthorize: {groups_left}')
else:
print('Complete! All security groups removed.')
break
for group in groups:
print(
f'Removing ingress from Group ID: {group["GroupId"]}, Group Name: {group["GroupName"]}'
)
for ingress in group['IpPermissions']:
new_group_id_pairs = list()
for user_group_id_pair in ingress['UserIdGroupPairs']:
print(user_group_id_pair)
if isinstance(user_group_id_pair, set):
list_ug = list(user_group_id_pair)
# Create a new user group pair list without a GroupName
new_ug = {}
key, value = None, None
for i, ug in enumerate(list_ug):
if i % 2 == 0:
key = ug[i]
else:
value = ug[i]
if key not in ['GroupName']:
new_ug[key] = value
elif isinstance(user_group_id_pair, dict):
new_ug = user_group_id_pair.copy()
if 'GroupName' in new_ug:
del new_ug['GroupName']
new_group_id_pairs.append(new_ug)
ingress['UserIdGroupPairs'] = new_group_id_pairs
kwargs = {
'DryRun': False,
'GroupName': group['GroupName'],
'IpPermissions': [ingress]
}
try:
r2 = ec2.revoke_security_group_ingress(**kwargs)
print(f'Revoked ingress: {ingress}')
except ClientError:
print(f'Error revoking ingress: {ingress}')
try:
ec2.delete_security_group(GroupId=group['GroupId'])
print(f'Success removing security Group ID {group["GroupId"]}, Group Name: {group["GroupName"]}!')
except ClientError:
print(f'Error removing security Group ID {group["GroupId"]}, Group Name: {group["GroupName"]}!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.