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

使用Terraform创建AWS子网报错:VPC ID不存在,求解决

问题

使用Terraform配置AWS资源时,创建子网报错,执行terraform apply后提示InvalidVpcID.NotFound: The vpc ID 'aws_vpc.MyVpc.id' does not exist,配置文件和错误信息如下:

配置文件main.tf

provider "aws" {
region = "us-east-1"
access_key = "---"
secret_key = "---"
}

resource "aws_instance" "MyWinServer"  {
ami = "ami-085d15593174f2582"
instance_type = "t2.micro"
tags = { Name = "WinServer"  }
}
resource "aws_vpc" "MyVpc" {
cidr_block = "10.0.0.0/16"
tags = { Name = "WinVpc"  }
}

resource "aws_subnet" "MySubnet" {
vpc_id = "aws_vpc.MyVpc.id"
cidr_block = "10.0.0.0/16"
}

错误信息

│ Error: error creating EC2 Subnet: InvalidVpcID.NotFound: The vpc ID 'aws_vpc.MyVpc.id' does not exist
│       status code: 400, request id: 2d384c58-2d02-4761-bcd2-1044a464a844
│
│   with aws_subnet.MySubnet,
│   on main.tf line 26, in resource "aws_subnet" "MySubnet":
│   26: resource "aws_subnet" "MySubnet" {

解决方法

错误核心是子网配置里的vpc_id被双引号包裹,Terraform会把带引号的"aws_vpc.MyVpc.id"当成普通字符串传给AWS API,而非解析为VPC资源的实际ID。

正确写法是去掉双引号,直接用Terraform的资源引用语法:

修改后的aws_subnet配置:

resource "aws_subnet" "MySubnet" {
vpc_id = aws_vpc.MyVpc.id  # 移除双引号,让Terraform解析VPC的实际ID
cidr_block = "10.0.0.0/24"  # 补充:子网CIDR必须是VPC的子集,不能和VPC完全一致,否则后续会报错
tags = { Name = "WinSubnet" }
}

额外提醒:子网的cidr_block必须是所属VPC网段的子集,你当前写的10.0.0.0/16和VPC完全重合,会触发新的错误,建议改为10.0.0.0/24这类子集网段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:35:32