Bootstrap FreeKB - Amazon Web Services (AWS) - Create Application Load Balancer (ALB) Listener Rules using Terraform
Amazon Web Services (AWS) - Create Application Load Balancer (ALB) Listener Rules 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. 

 

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
├── application_load_balancers (directory)
│   ├── provider.tf
│   ├── listeners.tf
│   ├── listener_rules.tf
│   ├── load_balancers.tf
│   ├── target_groups.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 assume you have already:

listener_rules.tf could have the following to create an Application Load Balancer Listener Rule to forward requests to foo.example.com onto my-target-group.

resource "aws_lb_listener_rule" "foo" {
  listener_arn = aws_lb_listener.alb-http-listener.arn
  priority     = 1

  action {
    type = "forward"
    target_group_arn = aws_lb_target_group.my-target-group.arn
  }

  condition {
    host_header {
      values = ["foo.example.com"]
    }
  }

}

 

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 bfa49b in the box below so that we can be sure you are a human.