Created
January 7, 2020 23:40
-
-
Save rjurney/ccdd0153e41ebc857470f3a77115a43d to your computer and use it in GitHub Desktop.
A script that removes all non-default security group rules and groups in a single REGION using boto3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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