Terraform创建AWS子网报InvalidVpcID.NotFound错误排查
故障原因
报错核心原因是脚本中多处属性引用错误,将资源的CIDR网段、关联VPC ID等属性值,错传给了要求传入资源唯一ID的参数:
- 子网资源的
vpc_id参数需要传入VPC的资源ID,但脚本传入了VPC的CIDR网段值10.0.0.0/16,AWS API识别到该值不是合法的VPC ID格式,直接返回不存在的报错。 - 你能在控制台看到对应
10.0.0.0/16网段的VPC,是因为Script_2里的VPC资源本身已经创建成功,故障仅出在后续资源的关联参数配置上。
逐处错误与修正方式
脚本中共存在4处参数引用错误,全部修正后即可正常创建资源:
aws_subnet.main 资源vpc_id参数错误
- 原错误写法:
vpc_id = "${aws_vpc.example.cidr_block}" - 修正为:
vpc_id = aws_vpc.example.id - 说明:aws_vpc资源的
id属性才是VPC的唯一标识符,cidr_block是VPC的网段配置值,不能作为ID传入。
- 原错误写法:
aws_route_table_association.public_rtable 资源subnet_id参数错误
- 原错误写法:
subnet_id = "${aws_subnet.main.*.vpc_id[count.index]}" - 修正为:
subnet_id = aws_subnet.main[count.index].id - 说明:该参数需要传入子网自身的资源ID,原写法取到的是子网关联的VPC ID,完全不符合参数要求。
- 原错误写法:
aws_route_table_association.public_rtable 资源route_table_id参数错误
- 原错误写法:
route_table_id = "${aws_route_table.rtable.vpc_id}" - 修正为:
route_table_id = aws_route_table.rtable.id - 说明:该参数需要传入路由表自身的资源ID,原写法取到的是路由表关联的VPC ID,无法匹配到路由表。
- 原错误写法:
aws_route_table.rtable 资源路由条目的gateway_id参数错误
- 原错误写法:
gateway_id = aws_internet_gateway.igw.vpc_id - 修正为:
gateway_id = aws_internet_gateway.igw.id - 说明:该参数需要传入互联网网关自身的资源ID,原写法取到的是互联网网关关联的VPC ID,无法匹配到网关。
- 原错误写法:
修正后Script_1完整代码
resource "aws_subnet" "main" { count = length(data.aws_availability_zones.azs.names) vpc_id = aws_vpc.example.id cidr_block = cidrsubnet(aws_vpc.example.cidr_block, 8, count.index) availability_zone = data.aws_availability_zones.azs.names[count.index] tags = { Name = "Public_Subnet_${count.index + 1}" } } resource "aws_route_table_association" "public_rtable" { count = length(data.aws_availability_zones.azs.names) subnet_id = aws_subnet.main[count.index].id route_table_id = aws_route_table.rtable.id } resource "aws_route_table" "rtable" { vpc_id = aws_vpc.example.id route { cidr_block = "0.0.0.0/0" gateway_id = aws_internet_gateway.igw.id } tags = { Name = "Internet_Gateway" } } resource "aws_internet_gateway" "igw" { vpc_id = aws_vpc.example.id tags = { Name = "My Internet gateway" } }
补充提示:Terraform对接AWS provider时,所有AWS资源的唯一标识符统一存储在资源的
id属性下,配置关联关系时注意区分资源自身ID、关联资源ID、配置属性(如CIDR、名称)的区别,不要混传。
内容的提问来源于stack exchange,提问作者Deepa
相关产品推荐
相关产品推荐

