Recently, while trying to create a Terraform stack for the infrastructure of an experimental app, I encountered a cryptic error:

Error: Error applying plan:

1 error(s) occurred:

* module.ecs.aws_ecs_service.current_task: 1 error(s) occurred:

* aws_ecs_service.current_task: InvalidParameterException: The target group with targetGroupArn arn:aws:elasticloadbalancing:eu-west-1:1111111111:targetgroup/xxx/xxxxxxxxxxxxxxx does not have an associated load balancer.
        status code: 400, request id: 5e027278-85ba-asdf-bd5b-cd67eda86a92 "test-apis"

After some research, I discovered that the error appears due to a race condition. Attempting to create an “aws_alb_target_group” Terraform resource without the underlying ALB (load balancer) being ready, triggers the error.

The solution (workaround) was simple, just enforce the order of resource creation using Terraform’s “depends_on” attribute.

For example:

resource "aws_lb" "this" {
  // ALB attributes here
}
resource "aws_alb_target_group" "frontend" {
  name = "frontend"
  port = 80
  protocol = "HTTP"
  vpc_id = xxxxx
  depends_on = [
    // Important bit is here
    aws_lb.this
  ]
}

Happy Terraforming!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.