需要找到一种方法来识别使用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 :(得分:1)
我认为0.0.0.0/0的路由不是Internet网关,那就是专用子网。专用子网可以路由到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'))
答案 1 :(得分:0)
这是在连接了虚拟专用网关的每个VPC中查找专用子网的最终工作代码。它检查专用子网是否在VPC的子网列表中,然后稍后将其保存以供另一个Lambda功能使用。这可能不是实现我的目标的最有效方法。渴望看到其他更好的解决方案。
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
def get_private_subnets():
priv_subnet_list = []
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:
priv_subnet_list.append(rs.get('SubnetId'))
return priv_subnet_list
def lambda_handler(event, context):
vpc_list = []
vpc_subnet_list = []
virtual_gateways = get_vpn_gateways()
lambda_subnets = []
# Get VPC Ids associated with the virtual private gateway
for virtual_gateway in virtual_gateways["VpnGateways"]:
vgwId = virtual_gateway["VpnGatewayId"]
vpcAttach = virtual_gateway["VpcAttachments"]
vpc_list.append(vpcAttach[0]["VpcId"])
# Get subnets within the VPC
for vpc in vpc_list:
subnets = get_vpc_subnets(vpc)
for subnet in subnets:
vpc_subnet_list.append(subnet.id)
# Get Private subnets from the subnet list
for privsubnet in get_private_subnets():
if privsubnet in vpc_subnet_list:
lambda_subnets.append(privsubnet)