Application Load Balancers in AWS rely on target groups to define where traffic is sent and how the health of destinations is evaluated. When Terraform is used to provision an ALB, the target group becomes the bridge between the load balancer and the backend resources. Understanding the configuration options, attachment patterns, and deployment workflow is essential for reliable infrastructure as code.
Introduction
Building an Application Load Balancer manually in the AWS Console involves creating a VPC, configuring subnets, setting up security groups, launching Amazon EC2 instances, creating a target group, adding listeners, and then verifying the whole setup. The process works but is time consuming and error prone. Terraform codifies that process.
In a typical lab workflow the goal is to provision an Application Load Balancer, launch two EC2 instances, register them in a target group, and test load balancing by refreshing the ALB DNS and observing traffic alternate between instances. The diagram for such a setup highlights one of the powerful capabilities of an ALB: routing traffic to different target groups using rules. This is commonly used for path-based routing for example /api vs /web or host-based routing in multi-service architectures.
For a simple exercise the focus is on a single target group with two EC2 instances.
Target Groups as Routing Endpoints
Target groups serve as the destination routing endpoint for Application Load Balancers and Network Load Balancers. They contain the configuration for registering targets such as EC2 instances, Lambda functions, or IP addresses, health checks, and traffic distribution rules.
The module uses a map-based approach for defining target groups, allowing multiple target groups to be created with different configurations. This approach is useful when the architecture requires separate routing for different services or paths.
Health checks are critical for determining whether targets can receive traffic. The configuration of health checks determines how the load balancer evaluates target availability and removes unhealthy destinations from rotation.
Target groups are the bridge between your load balancer and your backend resources. They define where traffic goes, how health is checked, and how connections are managed. Whether you're running EC2 instances, containers in ECS, Lambda functions, or IP-based targets, you need target groups to tie everything together.
Target Group Types Supported by ALB
Application Load Balancers support three target types, each suited to different architectures.
| Target Type | Description |
|---|---|
| instance | Routes to EC2 instances by instance ID. The ALB uses the instance's primary private IP. |
| ip | Routes to specific private IP addresses. Works with containers, cross-VPC targets, or on-premises resources via Direct Connect or Site-to-Site VPN. |
| lambda | Routes to Lambda functions. Only supported with ALBs. |
The instance target group is the most common type.
Module Scope and Prerequisites
A Terraform module containing common configurations for an AWS Application Load Balancer running over HTTP/HTTPS is available through the Terraform registry. The module is intended for creating a set of resources around an application load balancer: namely associated target groups and listeners.
Prerequisites for use include:
- You have created a Virtual Private Cloud and subnets where you intend to put this ALB.
- You have one or more security groups to attach to the ALB.
- Additionally, if you plan to use an HTTPS listener, the ARN of an SSL certificate is required.
The module supports both mutually exclusive options:
- Internal ALBs
- External ALBs
Note:
It's strongly recommended that the autoscaling module is instantiated in the same state as the ALB module as in flight changes to active target groups need to be propagated to the ASG immediately or will result in failure. The value of targetgroup[n][name] also must change any time there are modifications to existing targetgroups.
ALB has the ability to replace what several ELBs can do by routing based on URI matchers. Additionally, operating at layer 7 opens the ability to shape traffic using WAF.
A full example leveraging other community modules is contained in the examples/albtestfixture directory.
Configuration Workflow for ALB and Target Group
To manage AWS Application Load Balancers with Terraform ALB resources, follow the steps below:
- Configure the EC2 instances
- Create an ALB Target Group
- Add the ALB Target Group attachment
- Create an ALB Listener
- Manage custom ALB Listener rules
- Test the path-based routing on ALB
The full source code for the examples discussed is available.
Note: The example discussed is only for educational purposes, and using it in production environments is not recommended.
Configure EC2 Instances
We want to serve requests based on what path they are targeted at. Incoming requests can be classified based on whether:
- They are targeted toward the homepage
- They are registration requests
- They are related to images.
Each of the types described above needs to be served separately.
Provision three EC2 instances serving the corresponding requests, as seen in the Terraform configuration. The user_data attribute is used to supply a script that installs and runs the nginx service.
As far as target groups are concerned, recognizing them with paths is a matter of intent, which listener rules and EC2 instances should fulfill.
Create Target Groups
Target group creation is the step that defines where traffic goes, how health is checked, and how connections are managed.
A basic target group configuration example is provided in the module documentation. Health checks are critical for determining whether targets can receive traffic.
The module provides a comprehensive overview of target group configuration within the AWS Load Balancer Terraform module. This page covers configuration options, health checks, stickiness, advanced features, and integration examples. For information on listener rules that direct traffic to target groups, see Listener Rules and Traffic Routing.
Attach Instances to Target Groups
Add the configuration below to associate EC2 instances with the Target Groups:
- Instance A :: Target Group A
- Instance B :: Target Group B
- Instance C :: Target Group C
```hcl
resource "awslbtargetgroupattachment" "tgattachmenta" {
targetgrouparn = awslbtargetgroup.mytga.arn
targetid = awsinstance.instancea.id
port = 80
}
resource "awslbtargetgroupattachment" "tgattachmentb" {
targetgrouparn = awslbtargetgroup.mytgb.arn
targetid = awsinstance.instanceb.id
port = 80
}
resource "awslbtargetgroupattachment" "tgattachmentc" {
targetgrouparn = awslbtargetgroup.mytgc.arn
targetid = awsinstance.instancec.id
port = 80
}
```
Use terraform apply on the updated configuration, and make sure the instance placement is as intended in the target groups.
Create ALB Listener
Now that EC2 instances have been provisioned and placed in appropriate target groups, provision the ALB and configure the rules.
The resource awslb specified in the Terraform configuration provisions an ALB. The attribute loadbalancer_type specifies the type as “application”. Security groups and subnets already created with appropriate routing tables are specified.
Terraform Deployment Steps for ALB
Deploying an AWS Application Load Balancer using Terraform follows a repeatable workflow.
- Configure the EC2 instances
- Create an ALB Target Group
- Add the ALB Target Group attachment
- Create an ALB Listener
- Manage custom ALB Listener rules
- Test the path-based routing on ALB
In the project folder ALB-AWS-TEST in the terminal:
Initialize Terraform
Run:
terraform initReview the Execution Plan
Next, run:
terraform plan
This is one of the most important Terraform commands. It shows how many resources will be created, what configurations will be applied, the order Terraform will follow.
For this lab, you should see Terraform planning to create:
- 1 VPC
- 2 subnets
- 1 internet gateway
- 1 route table + associations
- 2 security groups
- 2 EC2 instances
- 1 Application Load Balancer
- 1 target group
- 1 listener
Always review the plan before applying. It’s your safety check.
- Deploy ALB with Terraform
If the plan looks good, deploy the infrastructure:
terraform apply
Terraform will show the plan again and ask: Do you want to perform these actions? Type: yes
Terraform will now start creating all the resources. This may take a few minutes, especially while waiting for the ALB to become active. You’ll see logs as each resource is created VPC → subnets → EC2 → ALB → target group → listener.
Get the ALB DNS Name
Once the deployment is complete, Terraform will display an output like the DNS name. Copy that DNS name and open it in your browser.Testing the AWS ALB Terraform Deployment
To test the Application Load Balancer, open the ALB DNS name in your browser and refresh the page multiple times.
Map-Based Target Group Definition
The module uses a map-based approach for defining target groups, allowing multiple target groups to be created with different configurations.
This design supports scenarios where different services require different health check settings, stickiness settings, or routing rules. The map structure lets the same module produce several target groups from a single input variable.
Health checks are critical for determining whether targets can receive traffic. Configuration options, health checks, stickiness, advanced features, and integration examples are covered in the module documentation.
Target groups serve as the destination routing endpoint for Application Load Balancers and Network Load Balancers. They contain the configuration for registering targets, health checks, and traffic distribution rules.
Integration Considerations
ALB has the ability to replace what several ELBs can do by routing based on URI matchers. Additionally, operating at layer 7 opens the ability to shape traffic using WAF.
When using ALB with ECS, HashiCorp provides example patterns.
The module is available through the Terraform registry and is built for common configurations for an AWS Application Load Balancer running over HTTP/HTTPS.
It is strongly recommended that the autoscaling module is instantiated in the same state as the ALB module as in flight changes to active target groups need to be propagated to the ASG immediately or will result in failure. The value of targetgroup[n][name] also must change any time there are modifications to existing targetgroups.
Conclusion
Terraform codifies the creation of AWS Application Load Balancer target groups and their attachment to backend resources. The workflow moves from VPC and subnet preparation, through EC2 provisioning, to target group definition with health checks and traffic distribution rules, then to listener creation and rule management.
The map-based definition model allows multiple target groups with distinct configurations to be generated from a single module input. Attachment resources bind specific instance IDs to target groups on specific ports, enabling precise control over placement.
Target group types supported by ALB cover instance routing, IP routing, and Lambda routing. The instance type remains the most common for EC2 backends.
Deployment safety is maintained through terraform init, terraform plan, and terraform apply. The plan stage reveals the intended creation of VPC, subnets, internet gateway, route tables, security groups, EC2 instances, ALB, target group, and listener. After apply, the ALB DNS name is used to validate load balancing behavior by refreshing the page and observing traffic distribution.
Consistent state between the ALB module and autoscaling module prevents failures during in-flight target group changes. Naming conventions for target_group[n][name] must be updated whenever target groups are modified.
These patterns provide a repeatable, code-driven approach to ALB target group management in AWS.