aws_lb Terraform Provisioning for Application Load Balancer Workloads

Infrastructure as Code changes how teams build Application Load Balancers. Manual creation through the AWS Console requires creating a VPC, configuring subnets, setting up security groups, launching Amazon EC2 instances, creating a target group, adding listeners, and then double checking everything because one small misconfiguration can break the whole setup. It works, but it is time consuming and not something you want to repeat every time you need a fresh environment. Defining the infrastructure in code with Terraform removes repetition and makes rebuilds predictable.

This article covers provisioning an Application Load Balancer with Terraform, using modules and lab patterns that demonstrate repeatable ALB deployments, listener rules, target groups, and integration with EC2.

Introduction

Terraform allows the definition of AWS resources as code and lets Terraform handle provisioning. Need to rebuild the lab? Just run terraform apply again and you are good to go. In a typical lab we 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 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 this exercise we keep things simple and focus on a single target group with two EC2 instances. The ALB will distribute incoming requests across both instances, and we validate the behavior by refreshing the DNS endpoint.

Prerequisites and Authentication

Before writing Terraform code, make sure your environment is ready. Terraform needs a way to authenticate to AWS so it can provision resources on your behalf. This setup was tested using Tutorials Dojo PlayCloud, but the same steps apply to any AWS account.

Your IAM user must have permissions to create:

  • VPC networking resources
  • EC2 instances
  • Application Load Balancers

Security Reminder: Never hardcode access keys inside Terraform files. This is a common cause of credential leaks. Always use secure credential management methods such as the AWS CLI configuration, environment variables, or IAM roles.

Create an IAM user for Terraform to allow Terraform to interact with AWS programmatically. In real-world environments, you should apply the principle of least privilege and grant only the required permissions.

How Terraform authenticates to AWS is through the credentials configured in the AWS CLI. When you run terraform init, terraform plan, terraform apply, Terraform uses those credentials.

After installation, verify that it is working by running:

terraform -version

If Terraform is installed correctly, the version number will appear in your terminal.

Editor Setup

For this lab, Visual Studio Code is used as the editor. The Terraform extension provides syntax highlighting, automatic formatting, basic validation. This makes writing and troubleshooting Terraform code much easier, especially when working with multiple resources like VPCs, subnets, security groups, EC2 instances, and load balancers.

Project Structure for AWS ALB Terraform

Before running terraform init and start provisioning resources, set up the project folder properly. Keeping the structure clean matters a lot, especially once your Terraform config starts growing.

Create a project folder for example alb-aws-test and place your Terraform files inside it.

A minimal layout for an ALB focused project can be:

alb-aws-test/ ├── main.tf ├── variables.tf ├── outputs.tf └── terraform.tfvars

Core Resources for an ALB Deployment

A complete ALB deployment with Terraform typically includes:

  • VPC and subnets where the ALB will be placed
  • Security groups attached to the ALB
  • EC2 instances to receive traffic
  • Target group to register instances
  • Application Load Balancer resource
  • Listener configuration

The Terraform module which creates Application and Network Load Balancer resources on AWS provides a wrapper for these resources. 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.

VPC and Subnet Requirements

The module supports both mutually exclusive:

  • Internal ALBs
  • External ALBs

You want to create a set of resources around an application load balancer: namely associated target groups and listeners. 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.

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.

ALB Routing and Listener Rules

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. AWS documentation has a more exhaustive set of reasons. Alternatively, if using ALB with ECS look no further than the HashiCorp example.

A Terraform module containing common configurations for an AWS Application Load Balancer running over HTTP/HTTPS is available through the Terraform registry. Branch build status is tracked for master.

The module is useful when:

  • You want to create a set of resources around an application load balancer: namely associated target groups and listeners.
  • 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.

A full example leveraging other community modules is contained in the examples/albtestfixture directory.

Module Capabilities and Constraints

Internal vs External

Attribute Internal ALB External ALB
Scheme internal internet-facing
Reachability private subnets only public internet
DNS private hosted zone public DNS name

The module supports both mutually exclusive options.

Listener Rule Actions

When using ALB Listener rules, ensure every rule resolves to an HTTP response.

  • forward action
  • redirect action
  • fixed-response action

This guarantees that every rule will resolve to some sort of an HTTP response.

Security Considerations

Using security groups to allow traffic only from the ALB improves security. ALB distributes traffic only to healthy targets. Health checks are evaluated by the target group and unhealthy instances are removed from rotation.

Key takeaways from operational use:

  • Terraform makes AWS deployments faster and repeatable
  • ALB distributes traffic only to healthy targets
  • Using security groups to allow traffic only from the ALB improves security
  • terraform destroy makes cleanup easy

Overall, this shows how Infrastructure as Code simplifies real cloud setups.

Integration with Lambda and WAF

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.

Manage Terraform better with Spacelift. Spacelift helps manage Terraform state, build more complex workflows, and supports policy as code, programmatic configuration, context sharing, drift detection, resource visibility, and many more.

An archaic, largely manual approach to IaC was hampering development, causing multiple bugs, and intensifying developers stress levels. Supported by Spacelift's laser-sharp UI clarity, minutely detailed documentation, and exceptional flexibility, TrueCar has transformed how it manages and deploys Terraform at scale today.

Terraform Licensing and Alternatives

Note: 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.

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

Deployment Workflow

Provisioning an Application Load Balancer using Terraform follows a repeatable workflow.

  • Define VPC, subnets, security groups in code
  • Define EC2 instances for the backend
  • Define target group and register instances
  • Define aws_lb resource and attach to subnets and security groups
  • Define listener on port 80 or 443
  • Apply configuration

After deployment, test load balancing by refreshing the ALB DNS and observing the traffic alternate between instances. By refreshing the ALB DNS and seeing the red and blue pages alternate, we confirmed that load balancing and health checks were working properly.

Cleanup is handled with terraform destroy. This is one of the biggest advantages of Infrastructure as Code, no manual cleanup needed.

Common Configuration Patterns

Typical attributes to consider for aws_lb:

Resource Typical Setting
loadbalancertype application
scheme internet-facing or internal
subnets public subnets for external, private for internal
security_groups allow inbound 80/443 from internet or specific CIDR
enabledeletionprotection false for lab, true for production

Target group health check settings influence whether traffic is sent to instances. Path, interval, timeout, healthy threshold and unhealthy threshold define behavior.

Listener rules can be built for path-based routing for example /api vs /web or host-based routing in multi-service architectures. This is commonly used for microservices where different hostnames route to different target groups.

Conclusion

In this AWS ALB Terraform lab we deployed an AWS Application Load Balancer using Terraform and placed two EC2 instances behind it. Instead of building everything manually in the AWS Console, we defined the VPC, subnets, security groups, EC2 instances, and ALB in code and deployed them with just a few commands.

The combination of Terraform module abstractions for ALB, listener rules with forward redirect or fixed-response actions, and target group health checking provides a repeatable pattern for layer 7 load balancing. Internal and external ALB support, integration with WAF and Lambda, and the ability to codify security groups around the load balancer make the approach suitable for both labs and production when extended with additional listener rules and WAF ACLs for security purposes.

Infrastructure as Code with Terraform reduces manual steps, improves consistency, and enables destroy and recreate cycles without manual cleanup. When the ALB DNS is refreshed and traffic alternates between healthy instances, the operational behavior of load balancing is verified directly from the deployed code.

Sources

  1. tutorialsdojo.com
  2. terraform-aws-modules
  3. TerraformFoundation
  4. spacelift.io

Related Posts