Terraform AWS Target Group Configuration and Traffic Management

Target groups are a powerful way to manage traffic to your AWS applications. They allow you to route 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 this article, we’ll show you how to create a target group using Terraform. We’ll cover the basics of target groups, and we’ll walk you through the steps of creating a target group in Terraform. We’ll also provide some tips on how to use target groups effectively.

By the end of this article, you’ll have a solid understanding of how to use target groups in Terraform. You’ll be able to create target groups to meet your specific needs, and you’ll be able to use them to improve the performance and reliability of your AWS applications.

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 you're running EC2 instances, containers in ECS, Lambda functions, or IP-based targets, you need target groups to tie everything together.

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

What Is a Target Group in AWS and Terraform

A target group is a logical grouping of EC2 instances that you can use to distribute traffic across multiple instances or to send traffic to a specific instance.

A target group is a logical grouping of resources that can be used to distribute traffic across multiple instances.

Target groups are used with load balancers to ensure that traffic is distributed evenly across your 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 your instances.

Target groups are a powerful tool for managing your EC2 instances and for ensuring that your applications are available and reliable.

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.

The real-world consequence for the user is that without a target group, a load balancer has no defined destination for incoming requests. The target group provides the routing logic and health awareness that makes the load balancer useful in production. The contextual connection is that the target group sits between the load balancer listener and the backend compute, making it the control plane for availability.

Core Properties of a Terraform Target Group

The name of the target group is a required identifier.

The port on which the target group listens is a required network parameter.

The protocol for which the target group is configured is a required traffic parameter.

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

The name property directly impacts AWS resource identification and must be unique within a region for the account. The port property determines which listener port the load balancer will forward to, and the protocol property determines the type of traffic inspection and health check behavior. Together these three properties form the minimum viable target group definition.

The impact layer for name is operational clarity in the AWS Management Console and in Terraform state. The impact layer for port is firewall and security group alignment. The impact layer for protocol is whether TLS termination happens at the load balancer or at the target.

Target Group Types Supported by Application Load Balancers

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 instance target type couples the ALB to EC2 instance metadata and allows automatic IP discovery when the instance is launched or replaced. The ip target type decouples the target from instance identity and is useful for ECS tasks, Fargate, or containers where the IP is the stable identifier. The lambda target type enables serverless backends without a traditional load balancer target.

The contextual layer connects target type selection to the choice of target_type in the aws_lb_target_group resource and to the ability to attach targets via aws_lb_target_group_attachment.

Creating a Target Group with the awslbtarget_group Resource

How to create a target group in Terraform?

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:

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

The resource block defines the logical grouping and its traffic parameters. The healthcheck block defines how the load balancer probes the target for availability. The targettype field explicitly selects instance routing.

The impact layer is that the user can now attach a load balancer listener to this group and begin routing production traffic. The contextual layer is that without the health check block, the load balancer would mark all targets as healthy by default, which defeats fault tolerance.

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

Terraform Configuration File Example with Health Check Settings

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

Initialize Terraform and apply the configuration.

Here is an example of a Terraform configuration file for a target group:

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

The healthcheckprotocol, healthcheckport, healthcheckpath, healthythreshold, unhealthythreshold, and timeout properties control the health probe behavior.

The impact layer for healthythreshold is that the target must pass two consecutive successful checks before being marked in service, reducing flapping. The impact layer for unhealthythreshold is that three consecutive failures remove the target from rotation, protecting users from serving errors. The timeout value of 5 seconds sets the maximum wait for a health response.

The contextual layer ties these settings to the health_check nested block syntax shown earlier and to the AWS load balancer health check model.

Attaching and Detaching EC2 Instances from a Target Group

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.
  • Initialize Terraform and apply the configuration.

The attachment is typically done with the aws_lb_target_group_attachment resource or with the targets block inside the target group resource.

An example of how to update the Terraform configuration file to remove an EC2 instance from a target group is:

hcl 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 targets { id = "${aws_instance.my-instance.id}" } }

hcl resource "aws_instance" "my-instance" { instance_type = "t2.micro" ami = "ami-0123456789abcdef0" subnet_id = "subnet-0123456789abcdef0" security_group_ids = ["sg-0123456789abcdef0"] }

For more information on removing EC2 instances from Terraform AWS target groups, please see the Terraform documentation.

The impact layer is that instance IDs become part of Terraform state, so adding or removing an ID triggers a plan change that updates the real AWS target registration. The contextual layer is that security groups and subnet placement must allow health check traffic from the load balancer to reach the instance on the specified port.

Q: How do I update the health check settings for a Terraform AWS target

The health check settings can be updated by modifying the healthcheck block or the healthcheckprotocol, healthcheckport, healthcheckpath, healthythreshold, unhealthy_threshold, and timeout attributes in the aws_lb_target_group resource, then running Terraform init and apply.

Listener Integration with a Target Group

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

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

The listener binds the load balancer front-end port to the backend target group. The default action sends all matching requests to the target group.

The impact layer is that traffic now flows from client to load balancer to target group to instance. The contextual layer is that the listener ARN and target group ARN must be consistent in region and VPC.

Troubleshooting Target Groups

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.

We hope that this blog post has been helpful. If you have any questions, please feel free to leave them in the comments below.

Key takeaways:

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

Troubleshooting involves verifying target registration, health check status, and listener rules. The AWS Management Console provides a visual health view. The AWS CLI allows scripted inspection of target health. The AWS API enables automation of diagnostics.

The impact layer is faster incident resolution when health checks fail or targets deregister unexpectedly. The contextual layer connects troubleshooting to the health check thresholds and timeout values previously defined.

Steps to Create a Target Group in Terraform

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.

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

The impact layer for the workflow is that infrastructure becomes reproducible and version controlled. The contextual layer is that the same configuration can be promoted across dev, staging, and production by changing variables.

Conclusion

Target groups are a powerful way to manage traffic to your AWS applications. They allow you to route 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 this article, we showed how to create a target group using Terraform. We covered the basics of target groups, and we walked through the steps of creating a target group in Terraform. We also provided some tips on how to use target groups effectively.

By the end of this article, you have a solid understanding of how to use target groups in Terraform. You are able to create target groups to meet your specific needs, and you are able to use them to improve the performance and reliability of your AWS applications.

Target groups remain 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 you're running EC2 instances, containers in ECS, Lambda functions, or IP-based targets, you need target groups to tie everything together.

The combination of name, port, protocol, target type, and health check configuration provides the complete definition needed for reliable traffic distribution. Terraform codifies these parameters into declarative resources, making target group lifecycle manageable through code.

Sources

  1. HatchJS
  2. OneUptime

Related Posts