Terraform中如何在EKS模块引用其他模块创建的VPC资源?
解决Terraform中"Reference to undeclared module"错误
问题原因
你的目录结构里,vpc和eks是同级的独立子目录,各自的main.tf中定义的是模块内部配置,但根目录(directory)没有将这两个模块声明为子模块统一管理,导致EKS模块所在文件无法直接引用VPC模块的输出值——Terraform仅识别当前模块或父模块中声明的模块。
解决方案一:根模块整合子模块(推荐)
通过在根目录创建配置文件,将VPC和EKS作为子模块引入,统一管理并传递参数:
- 在
directory目录下新建main.tf文件:
# 引入VPC子模块 module "vpc" { source = "./vpc" } # 引入EKS子模块并传递VPC参数 module "eks" { source = "./eks" vpc_id = module.vpc.vpc_id subnet_ids = module.vpc.private_subnets }
- 在
eks目录下新建variables.tf,定义接收参数:
variable "vpc_id" { type = string description = "VPC的ID,用于EKS集群部署" } variable "subnet_ids" { type = list(string) description = "EKS集群使用的私有子网ID列表" }
- 修改
eks/main.tf中的参数引用,替换为变量:
module "eks" { source = "terraform-aws-modules/eks/aws" version = "18.29.0" cluster_name = "other-tools-eks" cluster_version = "1.23" cluster_endpoint_private_access = true cluster_endpoint_public_access = true vpc_id = var.vpc_id subnet_ids = var.subnet_ids // remaining code }
解决方案二:远程状态共享(适用于多仓库/独立部署场景)
如果VPC和EKS需要分开部署,可以通过Terraform远程状态读取VPC的输出值:
- 确保VPC模块的状态已存储到远程后端(如S3)。
- 在
eks/main.tf中添加远程状态数据源:
data "terraform_remote_state" "vpc" { backend = "s3" config = { bucket = "你的Terraform状态存储桶名称" key = "vpc模块的状态文件路径" region = "us-east-1" } } module "eks" { source = "terraform-aws-modules/eks/aws" version = "18.29.0" cluster_name = "other-tools-eks" cluster_version = "1.23" cluster_endpoint_private_access = true cluster_endpoint_public_access = true vpc_id = data.terraform_remote_state.vpc.outputs.vpc_id subnet_ids = data.terraform_remote_state.vpc.outputs.private_subnets // remaining code }
注意:需根据实际使用的远程后端(如S3、Consul等)调整data块的配置。
内容的提问来源于stack exchange,提问作者Renz Carillo
相关产品推荐
相关产品推荐

