Terraform报错:如何将EC2实例ID用于for_each配置ALB目标组附件?
Terraform报错“Reference to undeclared resource”原因及解决方法
问题原因
Terraform的output是用来向外暴露模块内资源属性的(比如给父模块使用,或者通过terraform output命令查看),它本身不是可被内部资源引用的“资源类型”。你在同一个模块里直接引用output的值,相当于把output当成了资源来调用,这不符合Terraform的语法规则,所以会触发“未声明output类型资源”的报错。
解决方法
1. 单模块场景:直接引用EC2实例的属性
不需要通过output中转,直接在aws_lb_target_group_attachment的for_each里引用EC2实例资源的id属性即可。
错误写法
# 创建EC2实例 resource "aws_instance" "web" { count = 2 ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" } # 错误:试图用output捕获ID后在内部引用 output "ec2_instance_ids" { value = aws_instance.web[*].id } # 错误:引用output导致报错 resource "aws_lb_target_group_attachment" "web" { for_each = toset(output.ec2_instance_ids) target_group_arn = aws_lb_target_group.web.arn target_id = each.value }
正确写法
# 创建EC2实例 resource "aws_instance" "web" { count = 2 ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" } # 可选:如果需要对外暴露实例ID,保留output但内部不引用 output "ec2_instance_ids" { value = aws_instance.web[*].id } # 正确:直接引用EC2实例的id属性 resource "aws_lb_target_group_attachment" "web" { for_each = toset(aws_instance.web[*].id) target_group_arn = aws_lb_target_group.web.arn target_id = each.value }
2. 多模块场景:通过模块输出传递值
如果EC2实例是在子模块中创建的,需要先在子模块里声明output暴露实例ID,然后在根模块中通过module.xxx.output_name的方式引用。
子模块(modules/ec2/main.tf)
resource "aws_instance" "web" { count = 2 ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" } # 子模块声明output暴露实例ID output "instance_ids" { value = aws_instance.web[*].id }
根模块
# 调用子模块 module "ec2" { source = "./modules/ec2" } # 正确:引用子模块的output值 resource "aws_lb_target_group_attachment" "web" { for_each = toset(module.ec2.instance_ids) target_group_arn = aws_lb_target_group.web.arn target_id = each.value }
内容的提问来源于stack exchange,提问作者Mohamed Inshaf
相关产品推荐
相关产品推荐

