Need to find a way to identify AWS VPC Subnets that route through virtual private gateway by using Python Boto3. In another word, how can I use python boto3 to identify Private Subnets within a VPC?
The goal is to create a Lambda function that will identify private subnets within a given VPC, and then to launch another Lambda function within those Private Subnets.
Below is the code I got so far. It lists all subnets within a VPC that has a Virtual Private Gateway attached.
import boto3
def get_vpn_gateways():
ec2_client = boto3.client('ec2')
response = ec2_client.describe_vpn_gateways()
return response
def get_vpc_subnets(VpcId):
ec2 = boto3.resource('ec2')
vpc = ec2.Vpc(VpcId)
subnets = vpc.subnets.all()
return subnets
# Get VPC Ids associated with the virtual private gateway
vpc_list = []
virtual_gateways = get_vpn_gateways()
for virtual_gateway in virtual_gateways["VpnGateways"]:
vgwId = virtual_gateway["VpnGatewayId"]
vpcAttach = virtual_gateway["VpcAttachments"]
vpc_list.append(vpcAttach[0]["VpcId"])
for vpc in vpc_list:
print(vpc)
subnets = get_vpc_subnets(vpc)
for subnet in subnets:
print(subnet)
The code so far lists all the subnets within the VPC. I am thinking to use routetable as the key identifier for Private subnet. If there are routes going through VGW, then I will deem the subnet as Private. Does that make sense?