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

Terraform报错:未声明security-groups模块引用问题求助

问题:Terraform安全组模块输出引用报错

项目结构

├── deployment
│   ├── security-groups
│   │   ├── data.tf
│   │   ├── outputs.tf
│   │   ├── providers.tf
│   │   ├── sg-eks.tf
│   │   ├── terraform.auto.tfvars
│   │   └── variables.tf
│   └── vpc
│       ├── data.tf
│       ├── locals.tf
│       ├── main.tf
│       ├── outputs.tf
│       ├── providers.tf
│       ├── terraform.auto.tfvars
│       └── variables.tf
├── modules
│   ├── security-groups
│   │   ├── main.tf
│   │   ├── outputs.tf
│   │   └── variables.tf
│   └── vpc
│       ├── data.tf
│       ├── locals.tf
│       ├── main.tf
│       ├── outputs.tf
│       └── variables.tf

VPC模块配置(正常工作)

modules/vpc/outputs.tf

output "vpc_id" {
  description = "The VPC ID"
  value       = aws_vpc.vpc.id
}

output "public_subnets" {
  description = "List of IDs of public subnets"
  value       = values(aws_subnet.public)[*].id
}

output "private_subnets" {
  description = "List of IDs of private subnets"
  value       = values(aws_subnet.private)[*].id
}

deployment/vpc/outputs.tf

output "vpc_id" {
  description = "The VPC ID"
  value       = module.vpc.vpc_id
}

output "public_subnets" {
  description = "List of IDs of public subnets"
  value       = module.vpc.public_subnets
}

output "private_subnets" {
  value       = module.vpc.private_subnets
}

VPC模块的plan和apply操作正常,输出可在Terraform Cloud远程状态中调用。

安全组模块配置(报错场景)

modules/security-groups/outputs.tf

output "security_group_arn" {
  description = "The ARN of the security group"
  value       = values(aws_security_group.sg)[*].arn
}

deployment/security-groups/outputs.tf

output "security_group_arn" {
  description = "The ARN of the security group"
  value       = module.security-groups.security_group_arn
} 

执行时出现报错:

Reference to undeclared module No module call named "security-groups" is declared in the root module

已通过source "/barak-kalai/terraform-infra.git//modules/security-groups?ref=dev"引入模块,移除output配置后plan操作正常,说明模块本身调用无问题。

解决方案

报错核心原因:你在outputs.tf里引用的模块名称security-groups,和实际在deployment/security-groups目录下调用模块时定义的本地模块名称不一致。

修复步骤:

  1. 打开deployment/security-groups目录下的模块调用文件(比如sg-eks.tf),找到你定义的模块块,比如:

    module "sg_eks" {
      source = "/barak-kalai/terraform-infra.git//modules/security-groups?ref=dev"
      # 其他变量配置
    }
    

    这里的sg_eks就是该模块在当前根模块中的本地名称。

  2. 修改deployment/security-groups/outputs.tf中的引用,将module.security-groups替换为实际的本地模块名称,比如上面例子中的module.sg_eks:

    output "security_group_arn" {
      description = "The ARN of the security group"
      value       = module.sg_eks.security_group_arn
    } 
    
  3. 重新执行terraform plan验证,报错将消失,模块输出可正常被其他模块复用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 22:47:28