Skip to content

Instantly share code, notes, and snippets.

@arehmandev
Last active August 18, 2019 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arehmandev/8095305567b167a07bacd51c0fa549c0 to your computer and use it in GitHub Desktop.
Save arehmandev/8095305567b167a07bacd51c0fa549c0 to your computer and use it in GitHub Desktop.
Check if aws subnet is public - checks if internet gateway is attached to a route on a routetable of a subnet.
#!/usr/bin/env python3
# Quick script to create a dict of subnetid -> isPublic (check if AWS VPC subnet is public or not)
import boto3
ec2 = boto3.client('ec2')
subnetDict = {}
apicall = ec2.describe_route_tables()
for routeTable in apicall['RouteTables']:
associations = routeTable['Associations']
routes = routeTable['Routes']
for assoc in associations:
subnetId = assoc.get('SubnetId', '')
isPublic = False
for route in routes:
gatewayId = route.get('GatewayId', '')
if gatewayId.startswith('igw-'):
isPublic = True
if subnetId:
subnetDict[subnetId] = isPublic
print(subnetDict)
@jbdamask
Copy link

Thanks for posting this - it came in handy.

An issue I see is that multiple subnets can be associated with a RouteTable and your association loop assigns the last one in the collection to the subnetId var. The results in reporting only a single subnet for each route table. Maybe this is what you intended but if not, this adjustment reports all explicitly associated subnets:
` subnetDict = {}
apicall = ec2.describe_route_tables()

    for routeTable in apicall['RouteTables']:
        associations = routeTable['Associations']
        routes = routeTable['Routes']
        isPublic = False

        for route in routes:
            gid = route.get('GatewayId', '')
            if gid.startswith('igw-'):
                isPublic = True

        if(not isPublic):
            continue            

        for assoc in associations:
            subnetId = assoc.get('SubnetId', None)  # This checks for explicit associations, only
            if subnetId:
                subnetDict[subnetId] = isPublic

    if subnetDict:
        print(subnetDict)`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment