使用Terraform创建公有路由表时出现aws_internet_gateway未声明错误如何解决
错误原因
Terraform的不同模块之间资源作用域相互隔离,模块内部只能引用自身范围内定义的资源、输入变量和输出值,无法直接跨模块引用其他模块里的资源对象。你在public-rt模块的ressources.tf中直接引用了aws_internet_gateway.igw.id,但该IGW资源是在单独的igw模块中定义的,不在public-rt模块的作用域内,因此触发了未声明资源的报错。
另外你当前的路由规则配置也存在逻辑问题:指向VPC内部网段的路由默认由VPC本地路由实现,无需手动添加到公网路由表,公网路由表需要的是指向IGW的默认公网路由。
解决方案
- 第一步:在
../modules/rt路径下新建/修改variables.tf文件,添加gateway_id输入变量声明:
variable "vpc_id" { type = string description = "VPC ID to associate the route table with" } variable "vpc_cidr_block" { type = string description = "CIDR block of the VPC" } variable "gateway_id" { type = string description = "Internet gateway ID for public route" } variable "public_rt_tags" { type = map(string) description = "Tags for public route table" default = {} }
- 第二步:修改
../modules/rt/ressources.tf的路由表配置,替换硬编码的IGW引用为输入变量,同时修正路由规则:
# Routing table for public subnet resource "aws_route_table" "public" { vpc_id = var.vpc_id route { cidr_block = "0.0.0.0/0" gateway_id = var.gateway_id } tags = var.public_rt_tags }
- 第三步:修复根目录main.tf中的无效自引用配置,删除vpc和igw模块中不必要的自引用参数:
# Create VPC module "vpc" { source = "../modules/vpc" vpc_cidr_block = "************" vpc_tags = { Name = "prod-vpc" } } # Create IGW module "igw" { source = "../modules/igw" igw_tags = { Name = "prod-igw" } vpc_id = module.vpc.vpcId } # 其余子网、路由表模块配置保持原有即可,你当前public-rt模块已经正确传入了gateway_id参数
修改完成后重新执行terraform init、terraform plan验证配置即可。
内容的提问来源于stack exchange,提问作者bhamichi
相关产品推荐
相关产品推荐

