You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用AWS Boto3查询与Site-to-Site VPN关联的VPC及反向查询

通过AWS Boto3关联VPC与Site-to-Site VPN连接的解决方案

VPC和Site-to-Site VPN连接并非直接关联,二者通过**虚拟专用网关(VGW)**建立绑定关系。你之前调用的接口本身没问题,但需要通过VGW作为中间层来关联两者,以下是具体实现方案:

一、通过VPC ID获取对应的Site-to-Site VPN连接

步骤分为两步:先找到VPC关联的VGW,再通过VGW ID筛选对应的VPN连接。

import boto3

# 初始化EC2客户端
ec2_client = boto3.client('ec2')

def get_vpn_connections_by_vpc_id(vpc_id):
    # 1. 查询VPC绑定的虚拟专用网关(VGW)
    vgw_response = ec2_client.describe_vpn_gateways(
        Filters=[
            {'Name': 'attachment.vpc-id', 'Values': [vpc_id]}
        ]
    )
    if not vgw_response['VpnGateways']:
        return []
    
    vgw_id = vgw_response['VpnGateways'][0]['VpnGatewayId']
    
    # 2. 通过VGW ID查询关联的VPN连接
    vpn_response = ec2_client.describe_vpn_connections(
        Filters=[
            {'Name': 'vpn-gateway-id', 'Values': [vgw_id]}
        ]
    )
    return vpn_response['VpnConnections']

# 调用示例
target_vpc_id = 'vpc-12345678'
associated_vpns = get_vpn_connections_by_vpc_id(target_vpc_id)
print(f"VPC {target_vpc_id} 关联的VPN连接:{associated_vpns}")

二、通过Site-to-Site VPN连接获取关联的VPC

反向流程:先从VPN连接中提取绑定的VGW ID,再查询该VGW关联的VPC信息。

def get_associated_vpc_by_vpn_id(vpn_connection_id):
    # 1. 查询VPN连接详情,提取绑定的VGW ID
    vpn_response = ec2_client.describe_vpn_connections(
        VpnConnectionIds=[vpn_connection_id]
    )
    if not vpn_response['VpnConnections']:
        return None
    
    vgw_id = vpn_response['VpnConnections'][0]['VpnGatewayId']
    
    # 2. 查询VGW关联的VPC
    vgw_response = ec2_client.describe_vpn_gateways(
        VpnGatewayIds=[vgw_id]
    )
    if not vgw_response['VpnGateways'] or not vgw_response['VpnGateways'][0]['Attachments']:
        return None
    
    return vgw_response['VpnGateways'][0]['Attachments'][0]['VpcId']

# 调用示例
target_vpn_id = 'vpn-87654321'
associated_vpc = get_associated_vpc_by_vpn_id(target_vpn_id)
print(f"VPN连接 {target_vpn_id} 关联的VPC:{associated_vpc}")

关键说明

  • describe_vpcs和describe_subnets本身不包含VPN连接信息,因为VPN属于网络边界服务,与VPC的绑定关系存储在VGW资源中。
  • 确保你的Boto3客户端拥有ec2:DescribeVpnGateways和ec2:DescribeVpnConnections权限。

内容的提问来源于stack exchange,提问作者user24763718

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 22:27:28