Terraform AWS ALB侦听器规则路径

时间:2020-08-03 08:30:24

标签: amazon-web-services terraform aws-application-load-balancer

我正在尝试在我的ALB上设置一个侦听器规则,该规则应将/api路径路由到指定的目标组,但是由于某些原因,我似乎无法使它正常工作。

这是我的设置:

resource "aws_lb" "main" {
  name               = "${var.name}-alb-internal-${var.environment}"
  internal           = false
  load_balancer_type = "application"
  security_groups    = var.alb_security_groups
  subnets            = var.subnets.*.id

  tags = {
    Name        = "${var.name}-alb-${var.environment}"
    Environment = var.environment
  }
}

resource "aws_alb_target_group" "api" {
  name        = "${var.name}-tg-api-${var.environment}"
  port        = 8080
  protocol    = "HTTP"
  vpc_id      = var.vpc_id
  target_type = "ip"

  health_check {
    healthy_threshold   = "3"
    interval            = "30"
    protocol            = "HTTP"
    matcher             = "200"
    timeout             = "3"
    path                = var.health_check_path
    unhealthy_threshold = "2"
  }

  depends_on = [
    aws_lb.main,
  ]

  tags = {
    Name        = "${var.name}-tg-api-${var.environment}"
    Environment = var.environment
  }
}

resource "aws_alb_listener" "api" {
  load_balancer_arn = aws_lb.main.id
  port              = 80
  protocol          = "HTTP"

  default_action {
    type            = "fixed-response"

    fixed_response {
      status_code   = "404"
      content_type  = "text/plain"
      message_body  = "Hello world"
    }
  }
}

resource "aws_alb_listener_rule" "api_rule" {
  listener_arn = aws_alb_listener.api.arn
  priority     = 100

  action {
    type             = "forward"
    target_group_arn = aws_alb_target_group.api.arn
  }

  condition {
    path_pattern {
      values = ["/api/*"]
    }
  }
}

在此设置中,我尝试将以/api开头的每个请求转发到我的API目标组。我已经将固定的响应设置为侦听器的默认操作,并且故意将响应主体设置为“ Hello world”。

执行Forbidden时,我的API服务(在ECS中运行)返回GET /。因此,如果侦听器规则有效,我希望访问*.elb.amazonaws.com/api会返回Forbidden。但是,这些是我得到的结果:

*.elb.amazonaws.com/-> Hello World(正确)

*.elb.amazonaws.com/api-> Hello World(预期为“禁止”,即我的API服务的根路径的响应)

*.elb.amazonaws.com/api/health-> Not Found(期望“确定”,/health路径存在于我的API ECS服务上并返回200

我已经通过不使用侦听器规则成功测试了我的ECS API服务是否正常运行,并使侦听器默认操作直接进入目标组。

我如何将带有侦听器规则的任何/api请求成功转发到目标组?

1 个答案:

答案 0 :(得分:1)

我没有发现您的设置有任何问题。我认为所有工作都按预期进行:

  • '/'可以正常工作。这里没什么异常。
  • /api将默认为/,因此您将在观察时看到“ Hello World”。
  • /api/health将要求您的ecs服务/api/health,而不是/health。因此,如果您的ECS没有/api/health,您将得到Not Found