使用Terraform跨区域创建VPC对等连接时VPC ID不存在问题排查
排查跨区域VPC对等连接报错:West 1的VPC ID不存在
问题根源
你的代码存在两个核心问题引发报错:
- 跨区域对等未指定目标区域:创建
aws_vpc_peering_connection.peer时,引用了us-west-1区域的VPC作为对等端,但未添加peer_region参数。当前默认provider在us-west-2区域,AWS会尝试在该区域查找对应VPC ID,自然无法找到仅存在于us-west-1的VPC。 - 引用未定义的数据源:代码中使用
data.aws_caller_identity.peer.account_id获取账号ID,但未定义该数据源,会触发额外的资源找不到错误。
修复步骤及完整代码
1. 添加账号ID数据源
在代码开头添加data.aws_caller_identity,用于获取当前AWS账号ID:
data "aws_caller_identity" "current" {}
2. 补全VPC对等连接的区域参数
修改aws_vpc_peering_connection.peer资源,添加peer_region = "us-west-1"明确对等VPC所在区域,同时替换未定义的数据源引用:
# Requester's side of the connection. resource "aws_vpc_peering_connection" "peer" { provider = aws.us-west-2 vpc_id = aws_vpc.West_2.id peer_vpc_id = aws_vpc.West_1.id peer_region = "us-west-1" peer_owner_id = data.aws_caller_identity.current.account_id auto_accept = false tags = { Side = "Requester" } }
完整修复代码
# 获取当前AWS账号ID data "aws_caller_identity" "current" {} # Create VPC resource "aws_vpc" "West_1" { provider = aws.us-west-1 cidr_block = var.vpc_cidr_block_1 instance_tenancy = "default" enable_dns_support = true enable_dns_hostnames = true tags = { name = "West_1" } } # Create VPC resource "aws_vpc" "West_2" { cidr_block = var.vpc_cidr_block_2 instance_tenancy = "default" enable_dns_support = true enable_dns_hostnames = true tags = { name = "West_2" } } # Requester's side of the connection. resource "aws_vpc_peering_connection" "peer" { provider = aws.us-west-2 vpc_id = aws_vpc.West_2.id peer_vpc_id = aws_vpc.West_1.id peer_region = "us-west-1" peer_owner_id = data.aws_caller_identity.current.account_id auto_accept = false tags = { Side = "Requester" } } # Accepter's side of the connection. resource "aws_vpc_peering_connection_accepter" "peer" { provider = aws.us-west-1 vpc_peering_connection_id = aws_vpc_peering_connection.peer.id auto_accept = true tags = { Side = "Accepter" } } resource "aws_vpc_peering_connection_options" "requester" { # As options can't be set until the connection has been accepted # create an explicit dependency on the accepter. vpc_peering_connection_id = aws_vpc_peering_connection_accepter.peer.id requester { allow_remote_vpc_dns_resolution = true } } resource "aws_vpc_peering_connection_options" "accepter" { provider = aws.us-west-1 vpc_peering_connection_id = aws_vpc_peering_connection_accepter.peer.id accepter { allow_remote_vpc_dns_resolution = true } } provider "aws" { region = "us-west-2" default_tags { tags = { Provisioned = "Terraform" } } } provider "aws" { region = "us-west-1" alias = "us-west-1" default_tags { tags = { Provisioned = "Terraform" } } }
验证流程
- 执行
terraform init初始化Terraform环境 - 执行
terraform plan检查配置合法性,确认无报错 - 执行
terraform apply创建跨区域VPC对等连接资源
内容的提问来源于stack exchange,提问作者charles uneze
相关产品推荐
相关产品推荐

