09/08/2021, 5:01 PM
Hey everyone, is there a way to get the private and public subnets from an existing VPC using the look up method in Python?


09/08/2021, 5:48 PM
Hi Luis, the one way to tell the difference is to determine if a subnet has a route table route targeting an internet gateway. Having this route would mean its public. This isn't a great way to answer your question, programmatically. IMO the best way to identify public/private subnets is to use an arbitrary tag of your choice (eg- Type == Public/Private), then use that tag in a


09/08/2021, 6:08 PM
Thanks @green-stone-37839 I implemented something similar with Boto3 using the presence of the IGW or NAT in the routes table, but was wondering if there was already something implemented in Pulumi. Guess will port it to Pulumi using ec2 functions 🙂.
👍 1
Created this little python helper, in case anyone has the need to get public, private and isolated subnets from an existing VPC 🙂 (Code can be optimized 😅 ) :
import pulumi
import pulumi_aws as aws

INTERNET_ROUTE_TYPE_IGW = 'internet-gateway'

class PulumiNetworkHelper:

    def __init__(self) -> None:

    def __lookup_internet_route_type(self, routeTableId):
        route = aws.ec2.get_route(
            route_table_id = routeTableId,
            destination_cidr_block = ''
        if route == None or (not route.gateway_id and not route.instance_id and not route.nat_gateway_id):
            return INTERNET_ROUTE_TYPE_ISO
        if route.gateway_id:
            return INTERNET_ROUTE_TYPE_IGW
        if route.instance_id or route.nat_gateway_id:
            return INTERNET_ROUTE_TYPE_NAT
        return None

    def __get_subnets_by_internet_route_type(self, vpcId, internetRouteType):
        subnets = []
        routeTables = aws.ec2.get_route_tables( vpc_id = vpcId )
        for routeTableId in routeTables.ids:
            routeTable = aws.ec2.get_route_table( route_table_id = routeTableId )
            routeTableSubnets = [ association.subnet_id for association in routeTable.associations if association.subnet_id ]
            if (self.__lookup_internet_route_type(routeTableId) == internetRouteType):
                subnets = subnets + routeTableSubnets

        return subnets

    def get_isolated_subnets(self, vpcId):
        return self.__get_subnets_by_internet_route_type(vpcId, INTERNET_ROUTE_TYPE_ISO)

    def get_private_subnets(self, vpcId):
        return self.__get_subnets_by_internet_route_type(vpcId, INTERNET_ROUTE_TYPE_NAT)

    def get_public_subnets(self, vpcId):
        return self.__get_subnets_by_internet_route_type(vpcId, INTERNET_ROUTE_TYPE_IGW)
And in your pulumi stack just use it like this:
helper = PulumiNetworkHelper()
print ('Private Subnets:')
print (helper.get_private_subnets_from_vpc('vpc-abcd123')