Application Load Balancers in AWS are the workhorse for HTTP and HTTPS traffic distribution in modern architectures. When infrastructure is defined as code, the Terraform AWS modules for ALB provide a declarative way to model listeners, rules, target groups, and security groups in a single module invocation. The awslblistener resource is the core primitive that determines how incoming requests are accepted, inspected, and forwarded. Understanding how listeners interact with listener rules, default actions, and traffic routing priorities is essential for building reliable path-based and host-based routing without manual console drift.
Listener Fundamentals in the Terraform AWS ALB Module
The terraform-aws-modules/alb/aws module abstracts the creation of Application and Network Load Balancer resources on AWS. Within that module, listeners are configured using the listeners variable, which is a map of listener configurations.
Each listener definition specifies the port, protocol, and the default action to take for incoming traffic that doesn't match any rules. The module creates listeners using the AWS aws_lb_listener resource. You can configure multiple listeners for different ports and protocols. Each listener must have a default action, which can be one of the following types.
A typical listener map includes an HTTP to HTTPS redirect listener and a secure listener that forwards to a target group. The module example shows:
```hcl
module "alb" {
source = "terraform-aws-modules/alb/aws"
name = "my-alb"
vpc_id = "vpc-abcde012"
subnets = ["subnet-abcde012", "subnet-bcde012a"]
securitygroupingressrules = {
allhttp = {
fromport = 80
toport = 80
ipprotocol = "tcp"
description = "HTTP web traffic"
cidripv4 = "0.0.0.0/0"
}
allhttps = {
fromport = 443
toport = 443
ipprotocol = "tcp"
description = "HTTPS web traffic"
cidr_ipv4 = "0.0.0.0/0"
}
}
securitygroupegressrules = {
all = {
ipprotocol = "-1"
cidr_ipv4 = "10.0.0.0/16"
}
}
access_logs = {
bucket = "my-alb-logs"
}
listeners = {
ex-http-https-redirect = {
port = 80
protocol = "HTTP"
redirect = {
port = "443"
protocol = "HTTPS"
statuscode = "HTTP301"
}
}
ex-https = {
port = 443
protocol = "HTTPS"
certificatearn = "arn:aws:iam::123456789012:server-certificate/testcert-123456789012"
forward = {
targetgroupkey = "ex-instance"
}
}
}
targetgroups = {
ex-instance = {
nameprefix = "h1"
protocol = "HTTP"
port = 80
targettype = "instance"
targetid = "i-0f6d38a07d50d080f"
}
}
tags = {
Environment = "Development"
Project = "Example"
}
}
```
This configuration demonstrates how a listener on port 80 with protocol HTTP uses a redirect action to port 443 with status code HTTP_301, while the listener on port 443 with protocol HTTPS uses a forward action to a target group keyed as ex-instance.
When you're using ALB Listener rules, make sure that every rule's actions block ends in a forward, redirect, or fixed-response action so that every rule will resolve to some sort of an HTTP response.
How Traffic Flows Through an ALB Listener
Before diving into configuration details, it's important to understand how traffic flows through an AWS Application Load Balancer or Network Load Balancer.
A request arrives at the load balancer on a listener port and protocol. The listener evaluates rules in priority order. Rules are evaluated in order of priority, with the lowest number evaluated first. If no rule matches, the listener's default action is executed.
The module variable listeners is a map. Each entry defines port, protocol, and default action. Additional configuration such as certificate_arn is required when protocol is HTTPS.
The document explains how to configure listener rules and traffic routing within the terraform-aws-alb module. It covers the configuration of listeners, the creation of routing rules with various conditions, and the different types of actions that can be performed based on these rules. For information on configuring target groups that receive the traffic, see Target Group Configuration. For information about authentication methods, see Authentication Methods.
Listeners are configured using the listeners variable, which is a map of listener configurations. Each listener definition specifies the port, protocol, and the default action to take for incoming traffic that doesn't match any rules.
Sources: main.tf96-255
Listener Rules and Conditional Routing
Listener rules allow you to define conditional routing logic to determine how traffic is handled. Rules are evaluated in order of priority, with the lowest number evaluated first.
Rule conditions can be based on host header, path pattern, HTTP method, query string, and more. The action block for a rule can forward to a target group, redirect to another URL, or return a fixed response.
A common pattern is path-based routing. The diagram above 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 lab, we’ll keep things simple and focus on a single target group with two EC2 instances.
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 in this post is available here.
Note: The example discussed here is only for educational purposes, and using it in production environments is not recommended.
Deploying an ALB with Terraform End to End
Deploying an AWS Application Load Balancer using Terraform avoids manual console work. If you’ve tried building an ALB manually in the AWS Console, you already know the drill create a VPC, configure subnets, set up security groups, launch Amazon EC2 instances, create a target group, add listeners, and then double check everything because one small misconfiguration can break the whole setup. It works, but it’s time consuming and not something you want to repeat every time you need a fresh environment.
This is exactly where Terraform shines. Instead of clicking through multiple AWS console pages, you define your infrastructure in code and let Terraform handle the provisioning. Need to rebuild the lab? Just run terraform apply again and you’re good to go.
In this lab, we will:
Provision an Application Load Balancer
Launch two EC2 instances
Register them in a target group
Test load balancing by refreshing the ALB DNS and observing the traffic alternate between instances
The workflow for a reproducible deployment is:
- Configure EC2 instances
We want to serve requests based on what path they are targeted at. As the diagram above shows, 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.
Let’s provision three EC2 instances serving the corresponding requests, as seen in the Terraform configuration below.
We have used the user_data attribute to supply a script that installs and runs the nginx service
- Initialize the project
Make sure you are inside your project folder in the terminal.
Run:
bash
terraform init
- Review the execution plan
Run:
bash
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
If the plan looks good, deploy the infrastructure:
bash
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:
Copy that DNS name and open it in your browser.
- Testing the AWS ALB Terraform Deployment
Now for the best part.
To test the Application Load Balancer, open the ALB DNS name in your browser and refresh the page multiple times.
Each instance is configured with a Nginx web server, which responds uniquely.
Listener Configuration Options and Actions
The module supports the common listener actions required for production ALB setups.
| Action Type | Typical Use | Required Attributes |
|---|---|---|
| forward | Route to target group | targetgroupkey or targetgrouparn |
| redirect | HTTP to HTTPS or URL rewrite | port, protocol, status_code |
| fixed-response | Health check or deny | statuscode, contenttype, message_body |
The example simple listener configuration that redirects HTTP to HTTPS is:
hcl
listeners = {
ex-http-https-redirect = {
port = 80
protocol = "HTTP"
redirect = {
port = "443"
protocol = "HTTPS"
status_code = "HTTP_301"
}
}
}
When defining listener rules, the actions block must end in a forward, redirect, or fixed-response action so that every rule will resolve to some sort of an HTTP response.
A listener rule set can be expressed as:
hcl
listener_rules = {
rule1 = {
listener_key = "ex-https"
priority = 10
conditions = {
path_pattern = "/api/*"
}
actions = {
forward = {
target_group_key = "api-tg"
}
}
}
}
Priority is numeric, lower numbers are evaluated first. The module ensures rule creation order matches the priority.
Target Groups and Instance Registration
Target groups are defined under the target_groups variable. A minimal target group definition includes nameprefix, protocol, port, targettype, and target_id.
For instance targets, targettype is instance and targetid is the EC2 instance ID. For IP targets, target_type is ip.
The module creates target groups and attaches them to the listener via forward actions. The ALB Target Group attachment step ensures instances are registered and health-checked.
When building a multi-service architecture, separate target groups per service allow fine-grained routing. Path-based routing uses listener rules with path_pattern conditions to send /api requests to one target group and /web requests to another.
Security Group and Access Log Integration
The module allows securitygroupingressrules and securitygroupegressrules to be defined as maps. This avoids manual security group resource management.
Access logs can be enabled via the access_logs block with a bucket name. The ALB will deliver logs to the specified S3 bucket for audit and troubleshooting.
Tags are applied across resources via the tags map and can include Environment and Project metadata.
Operational Best Practices
Listener definitions should be versioned in code. Never edit ALB listeners via console in production environments that are managed by Terraform, as drift will be reverted on next apply.
Always test path-based routing on ALB after apply. Open the ALB DNS name in your browser and refresh the page multiple times to observe load balancing across registered targets.
Review the execution plan before applying. It’s your safety check against unintended resource replacement.
Use explicit priorities for listener rules. The lowest number is evaluated first. Avoid overlapping conditions that could cause ambiguous routing.
Conclusion
The awslblistener resource under the terraform-aws-modules/alb/aws module provides a declarative and repeatable way to model Application Load Balancer listeners, rules, and traffic routing. Listeners are defined as a map of port, protocol, and default action configurations. Listener rules add conditional routing based on host, path, and other conditions, evaluated by numeric priority.
Correct configuration requires each rule's actions block to end in a forward, redirect, or fixed-response action so that every rule will resolve to some sort of an HTTP response. Default actions on listeners guarantee a response for unmatched traffic.
End-to-end deployment involves provisioning VPC networking, EC2 instances, target groups, listeners, and security groups with Terraform init, plan, and apply. Testing is performed by accessing the ALB DNS name and observing traffic distribution across registered instances.
Using the module reduces manual console errors and enables consistent rebuilds of ALB environments for labs, staging, and production. The combination of listeners, rules, target groups, and Terraform state management delivers a reliable and auditable load balancing layer.