Terraform aws_lb Resource Deep Dive

The aws_lb resource is the Terraform entry point for provisioning load balancers in AWS. It manages a load balancer and serves as the foundation for declaratively configuring Application Load Balancers and Network Load Balancers, with listeners, target groups, routing rules and supporting services wired around it.

Resource Overview

awslb creates and manages the load balancer object in the AWS control plane. The resource is used with loadbalancertype set to application or network to instantiate the respective load balancer class. When loadbalancertype is set to application, the resource creates an ALB that is paired with awslblistener, awslbtargetgroup, and awslbtargetgroupattachment to complete the configuration.

Using the awslb and related resources from the AWS provider, you can declaratively configure ALBs, listeners, target groups, and routing rules in code. The attribute loadbalancer_type specifies the type as application. Security groups and subnets can be specified at creation time. Even though these few config lines are enough to create an ALB, further settings require more resource blocks.

Core Arguments and Constraints

The following arguments are supported for aws_lb.

Argument Description Valid values / Notes
internal Indicates whether the load balancer will be internal or internet-facing Optional boolean
loadbalancertype The type of the load balancer application, network
name The name of the load balancer Optional. Value length: From 1 to 32 symbols. Cannot be specified if name_prefix is set. The value can contain only Latin letters, numbers

The name constraint limits the value to Latin letters and numbers. The internal flag determines scope. The loadbalancertype flag determines the class of load balancer.

Application Load Balancer Purpose and Behavior

What is the purpose of ALB?

An Application Load Balancer distributes incoming HTTP and HTTPS traffic across multiple targets, such as EC2 instances, containers, or IPs, within one or more Availability Zones. Its purpose is to improve application availability, scale automatically with demand, and support advanced routing based on request content, such as URL paths or host headers. ALB also supports SSL termination and integrates with AWS services like ECS and WAF.

ALB operates at Layer 7 and routes HTTP HTTPS traffic based on content like paths and headers.

Application Load Balancer vs Network Load Balancer

An Application Load Balancer operates at Layer 7 and routes HTTP HTTPS traffic based on content like paths and headers, while a Network Load Balancer works at Layer 4 and handles TCP, UDP, and TLS traffic with ultra-low latency and static IP support.

Feature Application Load Balancer Network Load Balancer
Layer Layer 7 Layer 4
Protocols HTTP HTTPS TCP UDP TLS
Routing Based on request content, paths, host headers Based on IP and port
Latency Advanced routing Ultra-low latency
IP support Dynamic Static IP support

Declarative ALB Creation

A minimal ALB definition sets name, internal, loadbalancertype, security_groups and subnets.

hcl resource "aws_lb" "my_alb" { name = "my-alb" internal = false load_balancer_type = "application" security_groups = [var.vpc_sg] subnets = [var.subnet_a, var.subnet_b, var.subnet_c] tags = { Environment = "dev" } }

The example shows an internet-facing application load balancer with security groups and three subnets.

Internal Application Load Balancer Example

```hcl
resource "awsvpc" "example" {
cidr
block = "10.1.0.0/16"
tags = {
Name = "tf-vpc"
}
}

resource "awssubnet" "example" {
vpc
id = awsvpc.example.id
cidr
block = "10.1.1.0/24"
tags = {
Name = "tf-subnet"
}
}

resource "awslb" "alb" {
name = "tf-alb"
internal = true
load
balancertype = "application"
subnets = [aws
subnet.example.id]
tags = {
Name = "tf-alb"
}
}
```

For details about load balancers, see the user documentation.

Internet-Facing Network Load Balancer Example

```hcl
resource "awsinternetgateway" "example" {
vpcid = awsvpc.example.id
tags = {
Name = "tf-igw"
}
}

resource "aws_eip" "example" {
tags = {
Name = "tf-eip"
}
}

resource "awslb" "nlb" {
depends
on = [awsinternetgateway.example]
name = "tf-nlb"
internal = false
loadbalancertype = "network"
subnetmapping {
subnet
id = awssubnet.example.id
allocation
id = aws_eip.example.id
}
tags = {
Name = "tf-nlb"
}
}
```

Note This example uses the VPC and subnet defined in the Internal Application Load Balancer example.

Listeners and Default Actions

Listeners are attached to the load balancer via loadbalancerarn. The listener specifies a default action when none of the paths match.

hcl resource "aws_lb_listener" "my_alb_listener" { load_balancer_arn = aws_lb.my_alb.arn port = "80" protocol = "HTTP" default_action { type = "forward" target_group_arn = aws_lb_target_group.my_tg_a.arn } }

The default_action specified in the Listener resource block is essentially a default Listener Rule. It currently satisfies the default routing condition.

Custom Listener Rules

More rules can route requests to Target Groups B and C beyond the default target group A. 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.

HTTPS Configuration

How do I add HTTPS to my Terraform ALB?

Add an awslblistener resource on port 443 with protocol = HTTPS, attach an ACM certificate via certificatearn, and specify an SSL policy through sslpolicy to enforce modern TLS standards.

Web Application Firewall Integration

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 config below creates a simple WAF ACL:

hcl 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, add another resource block:

hcl 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 }

If you run terraform apply now, you should be able to see that WAF ACLs are configured for the ALB.

Module Context

Terraform module which creates Application and Network Load Balancer resources on AWS.

The module requirements are:

Name Version
terraform >= 1.5.7
aws >= 6.28
Name Version
aws >= 6.28

No modules.

The module resources include:

Name Type
awslambdapermission.this resource
aws_lb.this resource
awslblistener.this resource
awslblistener_certificate.this resource
awslblistener_rule.this resource
awslbtarget_group.this resource
awslbtargetgroupattachment.additional resource
awslbtargetgroupattachment.this resource
awsroute53record.this resource
awssecuritygroup.this resource
awsvpcsecuritygroupegress_rule.this resource
awsvpcsecuritygroupingress_rule.this resource
awswafv2webaclassociation.this resource
aws_partition.current data source

A sample parameter table shows:

Name Description Type Default Required
access_logs Map containing access logging configuration for load balancer object({ null no
additionaltargetgroup_attachments Map of additional target group attachments to create. Use targetgroupkey to attach to the target group created in target_groups map(object({ null no
associatewebacl Indicates whether a Web Application Firewall ACL should be associated with the load balancer bool false no
clientkeepalive Client keep alive value in seconds. The valid range is 60-604800 seconds

See patterns.md for additional configuration snippets for common usage patterns.

Conclusion

The awslb resource is central to building scalable, secure traffic ingress in AWS with Terraform. It provides a single declarative handle for both Application and Network Load Balancer types, with internal flag and loadbalancertype governing scope and class. The resource is intentionally minimal, requiring companion resources for listeners, target groups and attachments to deliver full routing. The pairing of awslb with awslblistener and awslbtargetgroup enables path and host based routing, SSL termination, and integration with WAF. Example patterns demonstrate internal ALBs for private services and internet-facing NLBs with subnet mappings and allocation IDs. Module usage adds structured defaults for access logs, web ACL association, client keep alive and additional target group attachments while enforcing that listener rules terminate in forward, redirect or fixed-response actions. Correct naming constraints, subnet selection and type choice ensure the load balancer matches the intended Layer 7 or Layer 4 traffic model. When combined with ACM certificates, WAF associations and security groups, awslb becomes the foundation for production grade, auditable load balancing defined entirely as code.

Sources

  1. docs.tf.k2.cloud
  2. spacelift.io
  3. github.com

Related Posts