Modularising ECS Service creation with optional ALB

What’s the best practice for handling this?

I want to be able to create ecs services with and without an ALB. I’m trying to create an ecs_service module that creates an ecs fargate service without an ALB and another module that attaches an ALB. Using aws_lb_target_group_attachment I cannot find a way to get the container IDs for the target_id argument.

I’m not trying to create the ALB first. Then pass a reference into my ecs service module and use make the aws_ecs_service.loadbalancer block and aws_security_group_rule ingress resource both dynamic blocks.

Being able to modularise ecs_service creation is this way seem like a common use case so I’m surprised it is this fiddly. Makes me feel I’m missing something obvious somewhere. Am I missing a general pattern? an argument or resource in the AWS provider? or something in the TF language?

Terraform is a declarative language, but you can emulate an if statement using the count parameter. Have a look at https://blog.gruntwork.io/terraform-tips-tricks-loops-if-statements-and-gotchas-f739bbae55f9#0223

Hi @marco-m, thanks for responding. Honestly I think my scenario is exposing a shortcoming in the AWS provider. It’s starting to look like it not me. IMO I should be able to create a module based in aws_ecs_service for creating an ECS service resource without an ALB. Then use aws_lb_target_group_attachment attach an ALB to that. But it doesn’t seem like there’s a datasource I can use to get the container ids requires by the attachment resource. The workaround that used what you suggested doesn’t work because depends_on doesn’t support modules.

I spoke too soon about the workaround not working because of the lack of depends_on support for modules. I’m surprised it works. I’ll share my config at some point.