Last active
August 18, 2019 13:53
-
-
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.
This file contains 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 | |
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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()