Skip to content

Instantly share code, notes, and snippets.

@rifelpet
Created March 27, 2019 17:08
Show Gist options
  • Select an option

  • Save rifelpet/a121d734f88d3316a2e37d271a4230cb to your computer and use it in GitHub Desktop.

Select an option

Save rifelpet/a121d734f88d3316a2e37d271a4230cb to your computer and use it in GitHub Desktop.
Unused AWS Security Group cleanup
#!/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