Search code examples
amazon-web-servicesterraformamazon-elastic-beanstalkaws-application-load-balancer

How to attach elastic beanstalk with shared load balancer's target group in Terraform?


I've created an Elastic Beanstalk environment resource and shared an Application load balancer resource using Terraform. The elastic beanstalk's environment resource is assigned to the application load balancer's ID using the Eb namespace settings.

The problem is the target group generated by elastic beanstalk is not set to the default listener rule. This is making the load balancer's URL show a 502 error when opened. It will run fine if I manage the default listener rule in the load balancer to forward the traffic to the Eb Target group.

So I'm searching for a way to assign the target group in Elastic Beanstalk to use the one created by the load balancer or let the load balancer's listener resource forward to the Elastic Beanstalk's target group by default. Using terraform.

Is there a way to do that? I searched everywhere and couldn't find a solution.

I tried to attach the load balance's listener with Elastic Beanstalk's target group or attach Elastic Beanstalk with the load balancer's target group using Terraform.

I expect the shared load balancer's listener to forward traffic to the elastic beanstalk's target group by default using the terraform template


Solution

  • I have figured it out. The logic was a bit wrong.

    So we don't need to specify the target group of elastic beanstalk to the load balancer. What we cab do is defining the shared load balancer in terraform as an elastic beanstalk environment property using the Setting block and specifying aws:elbv2:loadbalancer environment.

    The error 503 that occurs is because in the shared load balancer, elastic beanstalk uses its DNS as an Alias to route to the Load Balancer so the load balancer route the request to the right target group. This is done by marking the alias elastic beanstalk DNS record as Host header, which tells the load balancer "if there is a request coming from this DNS, then route it to the target group". Anything else will give error 503.

    But if we added the loadbalancer's endpoint as a host header as well, then it will work as well. This explains why using (wildcard) as a host header rule will let both of elastic beanstalk and the load balancer endpoints route to the application. But we can specify only one header in elastic beans environment, and doing wildcard rule will conflict with the other linked elastic beanstalk environments to the load balancer.

    In this case, we dont need to use the load balancer's endpoint, instead we rely on the DNS endpoint of each Elastic beanstalk environment, it will manage routing between instances by routing the requests to the load balancer.

    And this allows us to set a custom domain name to route to the elastic beanstalk environment DNS, not the load balancer's endpoint.