DEV Community

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

Posted on

1

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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay