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

Terraform AWS ALB模块反复修改同一规则,无法创建独立Listener规则

Terraform AWS ALB模块重复修改同一条Listener规则的问题解决

问题现象

使用terraform-aws-modules/alb/aws模块(版本~>8.6)创建内部ALB时,配置了两条HTTPS Listener规则:

  • 规则1:匹配特定主机头,转发到目标组
  • 规则2:匹配特定查询字符串,返回固定响应

但执行Terraform时,两条规则始终复用同一个ARN,反复修改,无法创建两条独立规则,出现循环更新的情况。

问题原因

  1. 查询字符串条件格式错误:第二条规则的query_strings条件使用了{ "bob" = "3" }的键值对格式,不符合模块预期的{ key = "bob", value = "3" }结构,导致模块无法正确计算规则的唯一标识,将两条规则识别为同一资源。
  2. 固定响应Action参数结构错误:第二条规则的fixed-response参数直接平级写在action里,未嵌套到fixed_response块中,不符合模块的参数要求。

修正后的Terraform代码

module "alb" {
  source  = "terraform-aws-modules/alb/aws"
  version = "~> 8.6"

  load_balancer_type = "application"
  internal           = true

  name    = "my-alb-int"
  vpc_id  = module.vpc.vpc_id
  subnets = module.vpc.private_subnets

  security_groups = [module.alb_sg.this_security_group_id]

  https_listeners = [
    {
      port            = 443
      protocol        = "HTTPS"
      certificate_arn = aws_acm_certificate.my_cert.arn
      action_type     = "fixed-response"
      fixed_response = {
        content_type = "text/plain"
        status_code  = "200"
        message_body = "Nothing to see here move along"
      }
    },
  ]

  https_listener_rules = [
    {
      https_listener_index = 0
      priority             = 100

      actions = [{
        type               = "forward"
        target_group_index = 0
      }]

      conditions = [{ 
        host_headers = ["my-host-header.example.com"] 
      }]
    },
    {
      https_listener_index = 0
      priority             = 5000

      actions = [
        {
          type = "fixed-response"
          fixed_response = {
            content_type = "text/plain"
            status_code  = 200
            message_body = "Something here"
          }
        }
      ]

      conditions = [{ 
        query_strings = [{ 
          key   = "bob"
          value = "3"
        }] 
      }]
    }
  ]

  target_groups = [
    {
      name_prefix          = "my-tg"
      backend_protocol     = "HTTPS"
      backend_port         = 443
      target_type          = "ip"
      deregistration_delay = 60
      health_check = {
        path                = "/"
        port                = "traffic-port"
        protocol            = "HTTPS"
        healthy_threshold   = 2
        unhealthy_threshold = 2
        timeout             = 5
        interval            = 30
      }
    }
  ]
}

关键修正点

  • 查询字符串条件:将{ "bob" = "3" }改为{ key = "bob", value = "3" },符合模块对query string条件的结构要求。
  • 固定响应Action:将content_type、status_code、message_body嵌套到fixed_response块中,与模块定义的action参数结构保持一致。

验证

修正后执行terraform plan,会看到两条独立的aws_lb_listener_rule资源被创建,各自拥有唯一的ARN,不再出现循环修改的情况。执行terraform apply后,ALB会存在两条优先级分别为100和5000的独立规则,分别对应预期的路由行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:02:45