Search code examples
amazon-web-servicesterraformamazon-ecsamazon-elbterraform-provider-aws

Terraform fails first time for ECS and Load Balancer


I am using Terraform to deploy my ECS cluster with Load Balancer. My Terraform code is as follows:

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 Service is linked with LoadBalancer as follows:

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
  }
}

When I apply the Terraform, it will create load balancer, target group and listener. However, Before creating the ECS service, it will throw this error:

...
...
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"

When I apply this terraform second time without changing anything, it will work perfectly. I don't know why it is failing for the first time.

How can I solve this issue?


Solution

  • This usually means that you need to explicitly define a depends_on relation with your ALB. Subsequently, you can try the following:

    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]
    }