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

如何从Terraform管理的EC2实例列表中提取ID用于ALB配置

问题根因

你使用for_each参数声明了EC2模块,所以module.ec2_private不是列表类型,而是键为字符串"0"、"1"的对象映射,无法使用列表索引语法或者element()函数读取属性。

修复方案

直接使用for_each对应的字符串键访问实例ID即可,修改ALB模块的targets配置如下:

targets = {
  my_app1_vm1 = {
    target_id = module.ec2_private["0"].id
    port      = 80
  },
  my_app1_vm2 = {
    target_id = module.ec2_private["1"].id
    port      = 8080
  }
}
优化方案(可选)

如果后续需要扩展实例数量,可使用for表达式动态生成目标配置,避免手动重复编写:

targets = {
  for idx_key, ec2_instance in module.ec2_private : "my_app1_vm${tonumber(idx_key) + 1}" => {
    target_id = ec2_instance.id
    # 按你的业务需求配置端口,示例为索引0用80,其余用8080
    port      = idx_key == "0" ? 80 : 8080
  }
}

内容的提问来源于stack exchange,提问作者Hernan Matias Agüero Ruiz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:18:02