python - 使用 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,那么我会将子网视为私有子网。那有意义吗?
解决方案
我认为 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'))
推荐阅读
- path-finding - 未遵循 mp_grid_path,对象飞走或不返回被动路径
- amazon-web-services - AWS Aurora Serverless 无法解释的写入 IOPS
- python - Python将文本文件值导入为浮点数
- java - JFreeChart 及时推进?
- angular - Angular Authguard 显示一个空白页面
- c# - C# HTTP 服务器访问被拒绝
- reactjs - 如何在 React 中等待 get 请求完成?
- git - 具有永久磁盘的 Docker 容器,如何在不关闭 Docker 容器的情况下进行变基
- java - 从 JavaFX LineChart 中消除空白
- npm - How to have hot reload when using "webpack serve" on Webpack 5