Terraform aws_lb Deep Dive for AWS Application Load Balancers

Terraform provides a declarative path to model AWS Application Load Balancers as infrastructure as code. The aws_lb resource is the entry point for creating the load balancer infrastructure itself, but a working ALB in production is never a single resource. The reference implementations consistently describe a relationship between three key components that must be defined together: the load balancer, the target group, and the listener. Understanding how aws_lb interacts with aws_lb_target_group and aws_lb_listener is essential for reliable traffic management away from individual instances and onto a managed service.

The Three Pillars of an ALB in Terraform

Defining an ALB in Terraform isn't just one resource block; it is a relationship between three key components.

  • The Load Balancer aws_lb
    This represents the load balancer infrastructure itself.
  • The Target Group aws_lb_target_group
    This resource decouples the load balancer from the actual instances.
  • The Listener aws_lb_listener
    This is the logic layer.

These three resources form a chain. The load balancer is created in subnets, the target group defines health and registration logic for backend targets, and the listener defines ports and routing actions. Terraform modules and cheatsheets emphasize that all three must be present for a functional ALB.

Core Resource aws_lb and Scope Configuration

The aws_lb resource represents the load balancer infrastructure itself.

Scope is controlled with internal. Setting internal = false creates an internet-facing load balancer. Internal ALBs are supported as a mutually exclusive option to external IP ALBs in module configurations.

Availability requires subnets from at least two different Availability Zones. If one zone goes down, the ALB continues to route traffic in the other. The module examples require a VPC and subnets where the ALB will be placed, typically subnets = ["subnet-abcde012", "subnet-bcde012a"] and vpc_id = "vpc-abcde012".

The following table summarizes the core attributes referenced in the sources.

Attribute Purpose Reference Note
name ALB name identifier alb_name = "my-alb"
internal Internet facing vs internal internal = false for internet-facing
subnets AZ distribution At least two AZs required
security_groups Attachment alb_security_groups = ["sg-edcd9784", "sg-edcd9785"]

Creating the ALB without a target group and listener leaves a working load balancer with no traffic routing.

Target Group Decoupling and Health Checks

The aws_lb_target_group resource decouples the load balancer from the actual instances. Instead of pointing the ALB at "Server A," you point it at a "Target Group," and you register servers to that group.

Health checks are critical. The health_check block continuously pings a path, e.g., /, to ensure the instance is healthy. If the check fails, the ALB automatically stops sending traffic to that specific node.

Operational steps outlined for ALB management include:

  • Configure the EC2 instances
  • Create an ALB Target Group
  • Add the ALB Target Group attachment
  • Create an ALB Listener

Target group configuration is often paired with a health check path such as health_check_path = "/". The module pattern shows logging configuration alongside the target group:

  • create_log_bucket = true
  • enable_logging = true
  • log_bucket_name = "logs-us-east-2-123456789012"
  • log_location_prefix = "my-alb-logs"

Tags are applied for ownership and environment tracking, e.g.:

"Terraform" = "true" "Env" = "${terraform.workspace}"

Listener Logic Layer and Routing Actions

The aws_lb_listener is the logic layer. It tells the ALB which ports to listen on, usually 80 or 443, and what to do with the traffic.

When 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.

Listener configuration examples include:

  • alb_protocols = ["HTTPS"]
  • certificate_arn = "arn:aws:iam::123456789012:server-certificate/test_cert-123456789012"

Path-based routing is a common use case. Incoming requests can be classified based on whether they are targeted toward the homepage, registration requests, or images. Each type needs separate serving.

The workflow for custom rules is:

  • Manage custom ALB Listener rules
  • Test the path-based routing on ALB

The sources note that configuring many more intricate Listener rules and WAF ACLs for security purposes is required for production, beyond educational examples.

Module Patterns and Registry Usage

Community modules encapsulate the three pillars into reusable patterns.

The Terraform AWS Modules ALB module creates Application and Network Load Balancer resources on AWS. The devops-workflow module contains common configurations for an AWS new style Load Balancer ALB/NLB and is available through the terraform registry.

A registry example shows the module invocation:

module "alb" { source = "terraform-aws-modules/alb/aws" alb_name = "my-alb" region = "us-east-2" alb_security_groups = ["sg-edcd9784", "sg-edcd9785"] vpc_id = "vpc-abcde012" subnets = ["subnet-abcde012", "subnet-bcde012a"] alb_protocols = ["HTTPS"] certificate_arn = "arn:aws:iam::123456789012:server-certificate/test_cert-123456789012" create_log_bucket = true enable_logging = true log_bucket_name = "logs-us-east-2-123456789012" log_location_prefix = "my-alb-logs" health_check_path = "/" tags { "Terraform" = "true" "Env" = "${terraform.workspace}" } }

Prerequisites for using the module include:

  • You want to create a set of resources for the ALB: namely an associated target group and listener
  • You've created a Virtual Private Cloud VPC + subnets where you intend to put this ALB
  • You have one or more security groups to attach to the ALB
  • You want to configure a listener for HTTPS/HTTP
  • You've uploaded an SSL certificate to AWS IAM if using HTTPS

The module supports both mutually exclusive options:

  • Internal IP ALBs
  • External IP ALBs

The README notes significant changes to the upstream module and that the README has not been updated yet.

A full example leveraging other community modules is contained in the examples/test_fixtures directory. The module has been packaged with awspec tests through test kitchen. To run them:

  • Install rvm and the ruby version specified in the Gemfile
  • Install bundler and the gems from our Gemfile
  • Ensure your AWS environment is configured for test and set TFVARregion to a valid AWS region

Always terraform plan to see your change before running terraform apply.

Integration with WAF, Logging, and Production Hardening

ALB Terraform refers to the use of Terraform to define and manage AWS Application Load Balancers.

Integration with AWS Web Application Firewall is described as a common production requirement. A Web Application Firewall is a security solution designed to protect web applications from various online threats and attacks. Its primary purpose is to enhance the security of web applications by monitoring, filtering, and blocking malicious traffic before it reaches the application.

The Terraform configuration for a simple WAF ACL is:

resource "aws_wafv2_web_acl" "my_waf" { name = "my-waf-acl" scope = "REGIONAL" default_action { allow {} } visibility_config { cloudwatch_metrics_enabled = false metric_name = "my-waf-metric" sampled_requests_enabled = false } }

To associate the WAF service with ALB:

resource "aws_wafv2_web_acl_association" "waf-alb" { resource_arn = aws_lb.my_alb.arn web_acl_arn = aws_wafv2_web_acl.my_waf.arn }

In this post, we saw how easy it is to configure, manage, and integrate the AWS ALB service with other services like Lambda functions and WAF. Please note that the example discussed here is only for educational purposes, and using it in production environments is not recommended. For production, you may have to configure many more intricate Listener rules and WAF ACLs for security purposes and create the Terraform ALB module.

Logging configuration is part of production hardening. The module supports create_log_bucket, enable_logging, and log location prefixing.

Operational Workflow and Testing

Managing AWS Application Load Balancers with Terraform ALB resources follows a sequence:

  • 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

EC2 provisioning often uses user_data to supply a script that installs and runs the nginx service. Each instance is configured with Nginx which responds uniquely.

Path-based routing is validated by classifying incoming requests and confirming responses from the correct backend.

Terraform state management at scale can be supported by tools that help manage Terraform state, build more complex workflows, and support policy as code, programmatic configuration, context sharing, drift detection, resource visibility, and many more.

Note on licensing: New versions of Terraform are placed under the BUSL license, but everything created before version 1.5.x stays open-source. OpenTofu is an open-source version of Terraform that expands on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6.

Conclusion

The aws_lb resource is the foundation of ALB infrastructure as code, but functional traffic management requires the coordinated definition of a load balancer, a target group with health checks, and a listener with routing actions. The three pillars pattern is reinforced across cheatsheets and community modules, with explicit guidance to use at least two AZ subnets, set internal correctly, and ensure listener rules terminate in forward, redirect, or fixed-response actions.

Module usage abstracts the wiring of target groups, listeners, logging, and security groups, and provides registry-ready examples with VPC prerequisites, certificate ARNs, and tagging. Production readiness adds WAF association, detailed listener rules, and logging buckets, all managed through Terraform with plan-before-apply discipline.

The authoritative content around aws_lb remains centered on these relationships and operational patterns rather than isolated resource definitions.

Sources

  1. BitSeByte Terraform Cheatsheet
  2. Terraform AWS Modules ALB
  3. DevOps Workflow Terraform AWS LB
  4. Spacelift Terraform ALB Blog

Related Posts