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

使用Terraform创建AWS Auto Scaling Group时遇对象列表属性访问错误

Terraform Validate错误:Unsupported Attribute 解决方法

错误信息

omkar@kws MINGW64 ~/repo/kiwi-infra (main)
$ terraform validate
╷
│ Error: Unsupported attribute
│
│   on main.tf line 46, in module "asg":
│   46:   tg = "${module.alb.tg}"
│     ├────────────────
│     │ module.alb is a list of object
│
│ Can't access attributes on a list of objects. Did you mean to access attribute "tg" for a specific element of the list, or across all elements of the list?

问题原因

你在调用ALB模块时设置了count = "${length(module.ec2.app)}",这会让module.alb变成列表类型的模块实例集合,而非单个模块对象。直接通过module.alb.tg访问属性会报错,因为列表本身没有tg属性,必须从列表的单个元素中提取。

解决方案

根据实际需求选择以下修改方式:

方式1:关联单个目标组(取第一个ALB实例的TG)

如果只需要将ASG关联到第一个ALB模块创建的目标组,修改main.tf中ASG模块的tg参数:

module "asg" {
  source = "./modules/asg"
  project = var.project
  app-sg = module.vpc.app-sg
  sn1 = module.vpc.sn1
  sn2 = module.vpc.sn2
  tg = module.alb[0].tg # 提取列表第一个元素的tg属性
}

同时明确ASG模块的变量类型,修改asg模块的变量定义:

variable "tg" {
  type = string # 单个目标组ARN为字符串类型
}

方式2:关联所有目标组(收集所有ALB实例的TG)

如果需要将ASG关联到所有ALB模块创建的目标组,用列表推导式收集所有实例的tg属性:

module "asg" {
  source = "./modules/asg"
  project = var.project
  app-sg = module.vpc.app-sg
  sn1 = module.vpc.sn1
  sn2 = module.vpc.sn2
  tg = [for alb_instance in module.alb : alb_instance.tg] # 收集所有ALB实例的TG ARN到列表
}

对应修改ASG模块的变量类型为字符串列表(匹配target_group_arns的参数要求):

variable "tg" {
  type = list(string) # 多个目标组ARN为字符串列表类型
}

补充说明

ASG的target_group_arns参数本身支持字符串列表,方式2可直接兼容多目标组场景;若确定只需要单个目标组,方式1更直接。建议使用Terraform新语法(去掉${}插值符号),代码更简洁易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 06:52:50