Bootstrap FreeKB - Amazon Web Services (AWS) - Create Application Load Balancer (ALB) Target Group using Terraform
Amazon Web Services (AWS) - Create Application Load Balancer (ALB) Target Group using Terraform

Updated:   |  Amazon Web Services (AWS) articles

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, a 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
├── elastic_load_balancers(directory)
│   ├── target_groups.tf
│   ├── target_groups_attachments.tf
│   ├── outputs.tf
│   ├── provider.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"
}

 

And target_groups.tf could have the following to create an Application Load Balancer Target Group.

resource "aws_lb_target_group" "my-application-load-balancer-target-group" {
  name = "my-target-group"
  port = 80
  protocol = "HTTP"
  vpc_id = data.terraform_remote_state.tfstate.outputs.my-vpc-id

  tags = {
    Name = "my-target-group"
  }
}

 

And target_groups_attachements.tf could have the following.

resource "aws_lb_target_group_attachment" "register-ec2-instances-in-target-group" {
  for_each = {
    "foo" = data.terraform_remote_state.tfstate.outputs.my-foo-instance-id
    "bar" = data.terraform_remote_state.tfstate.outputs.my-bar-instance-id
  }

  target_group_arn = aws_lb_target_group.my-application-load-balancer-target-group.arn
  target_id        = each.value
  port             = 80
}

 

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 Buy Me A Coffee



Comments


Add a Comment


Please enter fae2dd in the box below so that we can be sure you are a human.