如何使用Terraform将多台实例批量绑定到AWS LB目标组
问题原因
- 你尝试通过
module.test.test-[count.index]-id的方式动态拼接属性名调用模块输出,Terraform不支持这种语法,无法识别动态拼接的属性名 - 你配置的
count=2仅会创建2个绑定资源,无法覆盖3台实例的绑定需求
可行解决方案
方案1:基于本地值列表+count实现(适配你现有输出配置)
先定义本地值聚合所有实例ID,再通过count索引遍历绑定:
# 先聚合所有实例ID到本地列表 locals { test_instance_ids = [ module.test.test-1-id, module.test.test-2-id, module.test.test-3-id ] } # 批量绑定资源 resource "aws_lb_target_group_attachment" "test_node_instances" { count = length(local.test_instance_ids) target_group_arn = aws_lb_target_group.test_node_instances_group.arn target_id = local.test_instance_ids[count.index] port = 443 }
方案2:基于for_each实现(更稳定,避免实例增减时的索引偏移问题)
如果后续有实例增减需求,推荐用for_each替代count,避免索引变化导致的不必要资源重建:
locals { test_instance_ids = [ module.test.test-1-id, module.test.test-2-id, module.test.test-3-id ] } resource "aws_lb_target_group_attachment" "test_node_instances" { for_each = toset(local.test_instance_ids) target_group_arn = aws_lb_target_group.test_node_instances_group.arn target_id = each.value port = 443 }
优化建议
如果后续实例数量会频繁调整,建议你创建test实例模块时直接用count/for_each批量创建,模块输出直接返回实例ID列表,不需要单独定义每个实例的输出,后续绑定不需要手动修改本地值列表,可实现完全自动化扩容缩容。
内容的提问来源于stack exchange,提问作者dzbeda
相关产品推荐
相关产品推荐

