DEV Community

Cover image for Python script to find unused EC2 subnets
Ashiqur Rahman
Ashiqur Rahman

Posted on

Python script to find unused EC2 subnets

Recently, I was working on managing all VPC related resources using Terraform for all our AWS accounts. For one of the accounts, I stumbled upon a rather unpleasant situation where I saw a few hundred subnets in a region and I was left wondering whether all these subnets are actually in use.

Since, I am too lazy to go through them one by one manually, I wrote a python script to check which of these subnets are actually serving a purpose i.e has an ENI attached to it.

Step 1: List all subnets in our VPC

import subprocess
import json

def list_subnets(vpc_id):
    subnets = json.loads(subprocess.getoutput('aws ec2 describe-subnets'))['Subnets']

    def _filter(subnet):
        if subnet['VpcId'] == vpc_id:
            return True
        return False

    def _map(subnet):
        tags = subnet['Tags']
        name = ''
        for tag in tags:
            if tag['Key'] == 'Name':
                name = tag['Value']
        return {
            subnet['SubnetId']: (name, subnet['CidrBlock'], subnet['AvailabilityZone'], subnet['MapPublicIpOnLaunch'])
        }

    return list(map(_map, filter(_filter,subnets)))
Enter fullscreen mode Exit fullscreen mode

Step 2: Check if a subnet has an ENI attached

def check_if_subnet_has_enis_attached(subnet_id):
    cmd = f"aws ec2 describe-network-interfaces --filters Name=subnet-id,Values={subnet_id} --query 'NetworkInterfaces[*].Description'"
    enis = list(json.loads(subprocess.getoutput(cmd)))

    for eni in enis:
        if len(str(eni).strip()) == 0:
            enis.remove(eni)

    return enis

Enter fullscreen mode Exit fullscreen mode

Step 3: Find list of all unused subnets

if __name__ == '__main__':
    subnets = list_subnets()

    unused = []
    for subnet in subnets:
        for k, v in subnet.items():
            if len(check_if_subnet_has_enis_attached(k)) == 0:
                unused.append(subnet)

    print(unused)
Enter fullscreen mode Exit fullscreen mode

If you found this post helpful, CLICK BELOW 👇 Buy Me A Beer

Top comments (0)