How to determine the Container ID so that Terraform can attach it to an ALB target group

amazon-albamazon-ecsterraform

I've used Terraform to create a VPC, subnets, ECS instances, routing and a task definition which I am able to run via the AWS console. That gives me a few instances of my small web app running in multiple containers.

I have also been able to create a service using Application Load Balancers in the console but where I fail is when I try to automate that step. I can't attach the container to the target group using Terraform.

From the docs:

resource "aws_alb_target_group_attachment" "test" {
  target_group_arn = "${aws_alb_target_group.test.arn}"
  target_id = "${aws_instance.test.id}"
  port = 80
}

target_id (Required) The ID of the target. This is the Instance ID for an instance, or the container ID for an ECS container.

I don't know how to specify the container ID for an ECS container. In the console, the page where you register the container in the target group has a drop-down with my container identified as "nancy_template:0:5000".

"nancy_template" or "nancy_template:0:5000" both give me the error:

Error registering targets with target group

Where do I get the 'container ID' the docs say I need to populate the 'target_id' property?

Best Answer

I've managed to fix this!

I don't think you need to attach items to the target group yourself, which makes sense because it all happens magically when using the console wizard.

What I did was remove any attempts to attach any targets but define an ALB listener:

resource "aws_alb_listener" "web_front_end" {
  load_balancer_arn = "${aws_alb.nancy_template_alb.id}"
  port              = "80"
  protocol          = "HTTP"

  default_action {
    target_group_arn = "${aws_alb_target_group.web-targetgroup.id}"
    type             = "forward"
  }
}

and also added this to my service definition:

depends_on = [
  "aws_alb_listener.web_front_end",
]

..which might not be necessary but ensure that relationship between my target group and load balancer is in place before my service is brought up.

Related Topic