
An Elastic Load Balancer (ELB) is typically used to load balance requests across two (or more) different EC2 instances.
A Target Group contains:
- One or more EC2 instances using the EC2 instances ID
- One or more EC2 instances via IP address
- One or more EC2 instances via Lambda
- One or more Application Load Balancers (in other words, an group of Application Load Balancers)
This assumes you have setup Terraform with the Amazon Web Services (AWS) provider. If not, check out my article Amazon Web Services (AWS) Getting Started with Terraform.
Let's say you have the following files on your Terraform server.
├── required_providers.tf
├── network_load_balancers (directory)
│ ├── data.tf
│ ├── listener.tf
│ ├── load_balancer.tf
│ ├── outputs.tf
│ ├── provider.tf
│ ├── remote_states.tf
│ ├── target_group.tf
required_providers.tf will almost always have this.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
}
Let's say provider.tf has the following. In this example, the "default" profile in /home/username/.aws/config and /home/username/.aws/credentials is being used. This assumes you have setup Terraform as described in Amazon Web Services (AWS) - Getting Started with Terraform.
provider "aws" {
alias = "default"
profile = "default"
region = "default"
}
This assumes you have already:
- Created a Virtual Private Cloud (VPC) using Terraform or List Virtual Private Cloud (VPC) using Terraform
- Getting output variables using terraform_remote_state
target_group.tf could have the following.
resource "aws_lb_target_group" "my-target-group" {
name = "my-target-group"
port = 80
protocol = "TCP"
vpc_id = data.terraform_remote_state.virtual_private_clouds.outputs.my_vpc.id
tags = {
Name = "my-target-group"
}
}
target_type = "alb" can be used to create Target Group to forward requests from a Network Load Balance onto an Application Load Balancer.
resource "aws_lb_target_group" "nlb-to-alb-target-group" {
name = "nlb-to-alb-target-group"
port = 80
protocol = "TCP"
vpc_id = data.terraform_remote_state.virtual_private_clouds.outputs.my_vpc.id
target_type = "alb"
tags = {
Name = "nlb-to-alb-target-group"
}
}
Almost always, you will also:
- Create Network Load Balancer (ELB) Listener using Terraform
- Register Targets in a Target Group using Terraform
The terraform plan command can be used to see what Terraform will try to do.
terraform plan
And the terraform apply command can be used to create the Elastic Load balancer Target Group.
terraform apply
Did you find this article helpful?
If so, consider buying me a coffee over at