首页 > 解决方案 > 使用 Boto3 查找通过虚拟私有网关的子网路由

问题描述

需要找到一种方法来使用 Python Boto3 识别通过虚拟私有网关路由的 AWS VPC 子网。换句话说,如何使用 python boto3 来识别 VPC 中的私有子网?

目标是创建一个 Lambda 函数来识别给定 VPC 中的私有子网,然后在这些私有子网中启动另一个 Lambda 函数。

下面是我到目前为止得到的代码。它列出了 VPC 中附加了虚拟私有网关的所有子网。

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)

到目前为止的代码列出了 VPC 中的所有子网。我正在考虑使用路由表作为私有子网的关键标识符。如果有路由通过 VGW,那么我会将子网视为私有子网。那有意义吗?

标签: pythonaws-lambdaboto3

解决方案


我认为 0.0.0.0/0 的路由不是互联网网关,那是私有子网。私有子网可以路由到 NAT 网关或虚拟网关,但不能直接路由到 Internet 网关。所以,我写了如下代码。

import boto3

ec2 = boto3.resource('ec2')
route_tables = ec2.route_tables.all()

for route_table in route_tables:
    for ra in route_table.routes_attribute:
        if ra.get('DestinationCidrBlock') == '0.0.0.0/0' and ra.get('GatewayId') is None:
            for rs in route_table.associations_attribute:
                if rs.get('SubnetId') is not None:
                    print(rs.get('SubnetId'))

推荐阅读