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

Terraform中从多EC2实例ID取单个ID给ALB模块报错求助

问题解决:Terraform ALB目标组引用EC2实例ID错误

错误原因

你调用element和tolist函数时参数格式错误:

  • tolist()仅需传入一个集合参数,你错误地把索引0/1写到了tolist的参数列表里
  • element()需要两个参数:转换后的列表,以及目标索引,你的写法导致参数缺失

解决方案

有两种可靠的方式获取EC2实例ID:

方案1:修正函数调用格式

把element和tolist的调用分开,正确传递参数:

targets = {
  ec2_target = {
    target_id = element(tolist(module.ec2_instance), 0).id
    port = 80
  }
  my_other_target = {
    target_id = element(tolist(module.ec2_instance), 1).id
    port = 8080
  }
}

方案2:直接通过for_each键访问(推荐)

因为你用for_each = toset(["one", "two"])创建EC2实例,模块实例会以"one"和"two"作为键组成map,直接通过键访问更明确、稳定:

targets = {
  ec2_target = {
    target_id = module.ec2_instance["one"].id
    port = 80
  }
  my_other_target = {
    target_id = module.ec2_instance["two"].id
    port = 8080
  }
}

额外提示

注意第二个目标实例使用的是8080端口,请确保对应的EC2实例安全组允许ALB访问该端口,否则流量会无法正常转发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:05:56