需要找到一种使用Python Boto3识别通过虚拟专用网关路由的AWS VPC子网的方法。换言之,如何使用python boto3来标识专有网络内的私有子网?在
目标是创建一个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)
到目前为止,代码列出了专有网络内的所有子网。我正在考虑使用routetable作为私有子网的密钥标识符。如果有路由通过VGW,那么我将认为子网是私有的。有道理吗?在
我认为0.0.0.0/0的路由不是一个internet网关,那就是私有子网。专用子网可以路由到NAT网关或虚拟网关,但不能直接路由到internet网关。所以,我写了如下代码。在
下面是在每个连接了虚拟专用网关的VPC中查找私有子网的最终工作代码。它会检查私有子网是否在专有网络的子网列表中,然后继续保存它,以便稍后用于另一个Lambda函数。这可能不是实现我目标的最有效的方法。渴望看到其他更好的解决方案。在
相关问题 更多 >
编程相关推荐