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

Terraform AWS中无法访问ALB模块属性的问题咨询

问题:Terraform ALB模块无法访问https_listeners和target_groups属性

问题重现

执行terraform apply时出现属性访问错误,无法通过module.alb.https_listeners[0].arn和module.alb.target_groups[1].arn获取对应资源的ARN:

相关代码

module "alb" {
  source  = "terraform-aws-modules/alb/aws"
  version = "8.1.0"

  // ...

  target_groups = [
    {
       // ...
    },
    {
      name                 = "lb-number-one"
      backend_port         = 80
      backend_protocol     = "HTTPS"
      target_type          = "ip"
    }
  ]

  https_listeners = [
    {
      port               = 443
      protocol           = "HTTPS"
      certificate_arn    = aws_acm_certificate.this[0].arn
      target_group_index = 0
    }
  ]

  // ...

  https_listener_rules = [
    {
      actions = [{
        // ...
      }]

      conditions = [{
        // ...
      }]
    },
  ]
}

resource "aws_lb_listener_rule" "https_listeners" {
  listener_arn = module.alb.https_listeners[0].arn
  priority     = 100

  action {
    type             = "forward"
    target_group_arn = module.alb.target_groups[1].arn
  }

  condition {
    host_header {
      // ...
    }
  }
}

错误信息

╷
│ Error: Unsupported attribute
│ 
│   on alb.tf line 92, in resource "aws_lb_listener_rule" "https_listeners":
│   92:   listener_arn = module.alb.https_listeners[0].arn
│     ├────────────────
│     │ module.alb is a object
│ 
│ This object does not have an attribute named "https_listeners".
╵
╷
│ Error: Unsupported attribute
│ 
│   on alb.tf line 97, in resource "aws_lb_listener_rule" "https_listeners":
│   97:     target_group_arn = module.alb.target_groups[1].arn
│     ├────────────────
│     │ module.alb is a object
│ 
│ This object does not have an attribute named "target_groups".

原因分析

  1. 混淆模块输入参数与输出属性:代码中的target_groups、https_listeners是你传递给ALB模块的输入参数,但模块不会直接将输入参数作为对外暴露的输出属性。每个Terraform模块只会提供预先定义好的输出项供外部访问。
  2. 模块对象的属性限制:module.alb作为Terraform模块实例,本质是一个对象,其属性仅包含模块开发者定义的输出项。你试图访问的https_listeners和target_groups并不在该模块v8.1.0的输出列表中,因此触发“Unsupported attribute”错误。

解决方法

使用该ALB模块v8.1.0提供的正确输出属性:

  • 对于HTTPS监听器ARN,使用module.alb.https_listener_arns(列表类型,存储所有HTTPS监听器的ARN)
  • 对于目标组ARN,使用module.alb.target_group_arns(列表类型,存储所有目标组的ARN)

修正后的代码示例:

resource "aws_lb_listener_rule" "https_listeners" {
  listener_arn = module.alb.https_listener_arns[0]
  priority     = 100

  action {
    type             = "forward"
    target_group_arn = module.alb.target_group_arns[1]
  }

  condition {
    host_header {
      // ...
    }
  }
}

若不确定模块的输出项,可执行terraform state show module.alb查看该模块实例的所有可用输出属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 20:22:50