Created
March 27, 2019 17:08
-
-
Save rifelpet/a121d734f88d3316a2e37d271a4230cb to your computer and use it in GitHub Desktop.
Unused AWS Security Group cleanup
This file contains hidden or 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
| #!/usr/bin/env python3 | |
| import boto3 | |
| dryrun = True | |
| regions = boto3.client('ec2').describe_regions()['Regions'] | |
| for region in regions: | |
| print('\n\n{}\n\n'.format(region['RegionName'])) | |
| ec2 = boto3.client('ec2', region_name=region['RegionName']) | |
| sgs_paginator = ec2.get_paginator('describe_security_groups') | |
| for sgs in sgs_paginator.paginate(): | |
| for sg in sgs['SecurityGroups']: | |
| sg_id = sg['GroupId'] | |
| resp = ec2.describe_network_interfaces(Filters=[{'Name':'group-id', 'Values':[sg_id]}]) | |
| if len(resp['NetworkInterfaces']) == 0: | |
| print('{} {} {}'.format(sg.get('VpcId', ' ' * 12), sg_id, sg['GroupName'])) | |
| if not dryrun: | |
| ec2.delete_security_group(GroupId=sg_id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment