Terraform AWS Target Groups Configuration for Load Balancer Traffic Routing

Target groups are a powerful way to manage traffic to AWS applications. They allow routing traffic to different instances based on criteria such as the client’s IP address, the request’s port, or the request’s protocol. This can be useful for load balancing, fault tolerance, and more. In Terraform practice, target groups are the declarative definition that ties a load balancer to backend resources and controls how health is evaluated and how connections are managed. The configuration produced by Terraform creates a logical grouping that the load balancer consults on every request, and the real-world consequence for operators is that changes to instance health, capacity, or routing rules can be applied through versioned infrastructure code rather than manual console edits. The article that follows expands the reference facts into an operational view of how target groups are defined, how they behave with Application Load Balancers and Network Load Balancers, and how Terraform resources and module patterns express those behaviors.

What Target Groups Are and How They Function

Target groups are a logical grouping of EC2 instances that you can use to distribute traffic across multiple instances or to send traffic to a specific instance. Target groups are used with load balancers to ensure that traffic is distributed evenly across instances and to ensure that healthy instances are used to serve traffic. Target groups can be configured with different health checks to ensure that only healthy instances are used to serve traffic. You can also configure target groups with different weights to control how traffic is distributed across instances.

Target groups are a powerful tool for managing EC2 instances and for ensuring that applications are available and reliable. 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 running EC2 instances, containers in ECS, Lambda functions, or IP-based targets, you need target groups to tie everything together.

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.

Core Properties Defined in Terraform

Terraform exposes target group properties through the aws_lb_target_group resource. The reference material identifies three primary properties with examples.

Name Description Example
targetgroupname The name of the target group. resource "aws_lb_target_group" "example" { name = "my-target-group"}
port The port on which the target group listens. resource "aws_lb_target_group" "example" { port = 80}
protocol The protocol for which the target group is configured. resource "aws_lb_target_group" "example" { protocol = "HTTP"}

These properties form the baseline of any target group declaration. The name becomes the identifier used by listeners and attachments. The port determines the listening endpoint for inbound connections from the load balancer. The protocol determines how the load balancer interprets and forwards traffic to the targets.

Target Group Types Supported by Application Load Balancers

This guide covers the common target group types and configurations available in Terraform.

Application Load Balancers support three target types, each suited to different architectures:

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

Instance Target Group is the most common type.

The choice of target type determines registration mechanics and networking constraints. Instance type relies on AWS APIs to discover instance private IPs, which simplifies autoscaling groups. IP type is used when targets are not EC2 instances, such as ECS tasks with ENIs or external resources reachable over private connectivity. Lambda type enables direct invocation from the load balancer without a traditional network endpoint.

Creating a Target Group with awslbtarget_group

To create a target group in Terraform, you can use the aws_lb_target_group resource. The following example creates a target group for an HTTP load balancer:

resource "aws_lb_target_group" "my-target-group" { name = "my-target-group" port = 80 protocol = "HTTP" target_type = "instance" health_check { protocol = "HTTP" port = 80 path = "/" } }

This will create a target group named my-target-group that is configured for HTTP traffic and uses the HTTP protocol for health checks. The target group will be associated with all instances in the default VPC that have the port 80 open.

You can also use the aws_lb_target_group_attachment resource to attach instances to a target group.

A second canonical example shows expanded health check attributes:

resource "aws_lb_target_group" "my-target-group" { name = "my-target-group" port = 80 protocol = "HTTP" health_check_protocol = "HTTP" health_check_port = 80 health_check_path = "/" healthy_threshold = 2 unhealthy_threshold = 3 timeout = 5 }

For more information on creating Terraform AWS target groups, please see the Terraform documentation.

Health Checks and Traffic Distribution Rules

Health checks are critical for determining whether targets can receive traffic. Target groups can be configured with different health checks to ensure that only healthy instances are used to serve traffic. You can also configure target groups with different weights to control how traffic is distributed across instances.

The health check block defines protocol, port, and path used by the load balancer to probe targets. Healthy threshold and unhealthy threshold control how many consecutive successes or failures are required before a target changes state. Timeout controls the probe window.

The real-world impact is that unhealthy targets are removed from the request pool automatically, which prevents user-facing errors and supports rolling deployments. Weighting allows canary or blue-green patterns where a subset of capacity receives a proportion of traffic.

Module Pattern and Map-Based Configuration

The module uses a map-based approach for defining target groups, allowing multiple target groups to be created with different configurations.

Here's an example of a basic target group configuration:

Health checks are critical for determining whether targets can receive traffic.

The map-based approach lets operators define a collection of target groups with varying ports, protocols, health check paths, and stickiness settings in a single variable map. This reduces repetition and enables consistent naming and tagging across environments.

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.

This document provides a comprehensive overview of target group configuration within the AWS Load Balancer Terraform module. Target groups are essential components that define where your load balancer routes traffic and how it determines whether destinations are healthy. This page covers configuration options, health checks, stickiness, advanced features, and integration examples.

Attaching Instances and Targets

Q: How do I add EC2 instances to a Terraform AWS target group?

A: To add EC2 instances to a Terraform AWS target group, you can use the following steps:

  • Update the Terraform configuration file to include the IDs of the EC2 instances that you want to add.

The aws_lb_target_group_attachment resource is the mechanism for binding specific instance IDs or IP addresses to a target group after the group exists. This decouples target registration from target group definition and supports dynamic attachment from data sources or outputs.

Listener Integration and Traffic Routing

The following example creates a listener for an HTTP load balancer that uses the target group created in the previous example:

resource "aws_lb_listener" "my-listener" { load_balancer_arn = aws_lb.my-load-balancer.arn port = 80 protocol = "HTTP" default

Listeners evaluate incoming requests and forward them to target groups based on rules. For information on listener rules that direct traffic to target groups, see Listener Rules and Traffic Routing.

Operational Workflow with Terraform

Create a Terraform configuration file that defines the target group’s properties.

Initialize Terraform and apply the configuration.

The workflow reflects infrastructure as code principles: the configuration file becomes the source of truth for name, port, protocol, and health check settings. Initialization resolves provider plugins and module dependencies. Apply creates the target group in AWS and registers the configuration with the load balancer.

Key takeaways from the reference material:

  • A target group is a logical grouping of resources that can be used to distribute traffic across multiple instances.
  • Target groups can be used with load balancers to distribute traffic evenly across multiple instances.
  • Terraform can be used to create target groups in AWS.
  • To create a target group using Terraform, you need to specify the following information:
    • The name of the target group
    • The protocol that the target group will use
    • The port that the target group will use
    • The health check settings for the target group
  • You can troubleshoot target groups by using the following tools:
    • The AWS Management Console
    • The AWS CLI
    • The AWS API

Q: What is a Terraform AWS target group?

A: A Terraform AWS target group is a resource that defines a collection of EC2 instances that can receive traffic from an Application Load Balancer. Target groups can be used to distribute traffic evenly across multiple EC2 instances, or to route traffic to specific instances based on criteria such as the instance’s health status or the request’s source IP address.

Q: How do I create a Terraform AWS target group?

A: To create a Terraform AWS target group, you can use the following steps:

  • Create a Terraform configuration file that defines the target group’s properties.
  • Initialize Terraform and apply the configuration.

We covered the basics of target groups, including what they are and how they work. We then showed you how to create a target group using Terraform, and we provided some tips for troubleshooting.

Troubleshooting and Visibility

You can troubleshoot target groups by using the following tools:

  • The AWS Management Console
  • The AWS CLI
  • The AWS API

The console provides target health visualizations and CloudWatch metrics. The CLI enables programmatic inspection of target health, deregistration, and attachment status. The API supports automation for remediation workflows.

Conclusion

Target groups in Terraform are the declarative control plane for how Application Load Balancers and Network Load Balancers decide where requests go and which backends are considered healthy. The aws_lb_target_group resource captures name, port, protocol, target type, and health check parameters that together define a traffic destination. The three target types supported by Application Load Balancers - instance, ip, and lambda - expand the pattern beyond EC2 to containers, private IP targets, and serverless functions. Map-based module configurations allow multiple target groups to be generated from a single variable definition, preserving consistency across environments. Health checks with thresholds and timeouts ensure that only healthy targets receive traffic, and weighting provides fine-grained distribution control. Attachment resources separate target group definition from target registration, enabling dynamic scaling and autoscaling group integration. Listener resources complete the data path by associating a load balancer with a target group. The operational result is a fully codified, auditable, and repeatable traffic routing layer that improves performance and reliability of AWS applications.

Sources

  1. HatchJS Terraform AWS Target Group
  2. OneUptime Create Target Groups with Terraform
  3. DeepWiki Terraform AWS Modules ALB Target Group Configuration

Related Posts