CodexBloom - Programming Q&A Platform

Terraform: Scaling ECS Services with Application Load Balancer and Dynamic Target Groups

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
terraform aws ecs load-balancer hcl

I've hit a wall trying to I'm having trouble with I'm confused about I'm optimizing some code but I'm currently trying to set up an AWS ECS service with an Application Load Balancer (ALB) that dynamically scales based on the health of my application containers..... I have a basic structure in place, but I'm encountering issues when I attempt to configure multiple target groups for different paths on the same ALB. The goal is to route traffic based on path patterns to different ECS services. Here's what I've tried so far: 1. Defined an ALB with a listener that listens on port 80. 2. Created two target groups for different path patterns, but I'm not sure how to link them correctly to the listener. 3. Used dynamic blocks in Terraform to create the target groups, but I'm facing an issue where only one of the target groups seems to be recognized by the ALB listener. Here's a snippet of my current configuration: ```hcl resource "aws_lb" "my_alb" { name = "my-alb" internal = false load_balancer_type = "application" security_groups = [aws_security_group.alb_sg.id] subnets = aws_subnet.my_subnets[*].id } resource "aws_lb_target_group" "target_group_a" { count = var.enable_target_group_a ? 1 : 0 name = "tg-a" port = 80 protocol = "HTTP" vpc_id = aws_vpc.my_vpc.id } resource "aws_lb_target_group" "target_group_b" { count = var.enable_target_group_b ? 1 : 0 name = "tg-b" port = 80 protocol = "HTTP" vpc_id = aws_vpc.my_vpc.id } resource "aws_lb_listener" "front_end" { load_balancer_arn = aws_lb.my_alb.arn port = "80" protocol = "HTTP" default_action { type = "forward" target_group_arn = aws_lb_target_group.target_group_a[0].arn } dynamic "default_action" { for_each = [ { target_group = aws_lb_target_group.target_group_a[0].arn, path_pattern = "/api/*" }, { target_group = aws_lb_target_group.target_group_b[0].arn, path_pattern = "/static/*" } ] content { type = "forward" target_group_arn = default_action.value.target_group } } } ``` Despite running `terraform apply`, I receive the following error: ``` Error: Invalid target group provided. Target group must be a valid target group ARN. ``` I suspect that the dynamic block for the `default_action` is not generating the expected configuration for multiple target groups. Can anyone provide insight on how to properly set up multiple target groups with path-based routing in Terraform for my ALB? Additionally, any best practices on configuring ECS services with ALB would be appreciated. How would you solve this? Thanks, I really appreciate it! What's the correct way to implement this? Has anyone dealt with something similar? This is my first time working with Hcl stable. Hoping someone can shed some light on this. I'm developing on Ubuntu 20.04 with Hcl.