ECS 和负载均衡器的 Terraform 第一次失败

Terraform fails first time for ECS and Load Balancer

我正在使用 Terraform 部署带有负载均衡器的 ECS 集群。我的 Terraform 代码如下:

resource "aws_lb" "my_lb" {
  name               = format("%s-my-lb", var.name)
  internal           = false
  load_balancer_type = "application"
  security_groups    = [var.lb_security_groups_id]
  subnets            = var.public_subnet_id
}
...
resource "aws_lb_target_group" "my_tg" {
  name        = format("%s-my-tg", var.name)
  port        = 80
  protocol    = "HTTP"
  target_type = "ip"
  vpc_id      = var.vpc_id
}
...
resource "aws_lb_listener" "my_listener" {
  load_balancer_arn = aws_lb.my_lb.arn
  port              = "80"
  protocol          = "HTTP"
  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.my_tg.arn
  }
}

ECS 服务与 LoadBalancer 链接如下:

resource "aws_ecs_service" "my_ecs_service" {
  name                               = format("%s-ecs-service", var.name)
  ...
  ...
  load_balancer {
    target_group_arn = aws_lb_target_group.my_tg.arn
    container_name   = "my-container"
    container_port   = 80
  }
}

当我应用 Terraform 时,它会创建负载平衡器、目标组和侦听器。但是,在创建ECS服务之前,它会抛出这个错误:

...
...
aws_lb_target_group.my_tg: Creation complete after 8s [id=arn:aws:elasticloadbalancing:us-east-1:xxxxxxxx:targetgroup/my-tg/7885700988492baf]
...
...
aws_ecs_service.my_ecs_service: Still creating... [1m40s elapsed]
aws_lb.my_lb: Still creating... [2m0s elapsed]
aws_ecs_service.my_ecs_service: Still creating... [1m50s elapsed]
aws_lb.my_lb: Creation complete after 3m10s [id=arn:aws:elasticloadbalancing:us-east-1:xxxxxxxx:loadbalancer/app/my-lb/b904f34fcc0f90ef]
aws_lb_listener.clinician_listener: Creating...
aws_lb_listener.clinician_listener: Creation complete after 3s [id=arn:aws:elasticloadbalancing:us-east-1:xxxxxxx:listener/app/my-lb/b904f34fcc0f90ef/5e08c22d4c61a26b]

Error: InvalidParameterException: The target group with targetGroupArn arn:aws:elasticloadbalancing:us-east-1:290786573471:targetgroup/gwell-QA-clinician-tg/7885700988492baf does not have an associated load balancer. "my-ecs-service"

当我第二次应用这个 terraform 而不做任何更改时,它将完美地工作。不知道为什么第一次失败

我该如何解决这个问题?

这通常意味着您需要明确定义与 ALB 的 depends_on 关系。随后,您可以尝试以下操作:

resource "aws_lb_target_group" "my_tg" {
  name        = format("%s-my-tg", var.name)
  port        = 80
  protocol    = "HTTP"
  target_type = "ip"
  vpc_id      = var.vpc_id

  depends_on = [aws_alb.my_lb]
}