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

Let's say you want to forward requests onto different Target Groups based on the URL. For example:

  • www.example.com -> www Target Group
  • foo.example.com -> foo Target Group
  • bar.example.com -> bar Target Group

HTTP Host Header can be used. listener_rules.tf could have the following to create an Application Load Balancer Listener Rule to forward requests based on the HTTP Host Header.

resource "aws_lb_listener_rule" "alb_http_listener_rules" {

  for_each = {
    "www.example.com" = ["1", aws_lb_target_group.target-groups["www-target-group"].arn]
    "foo.example.com" = ["2", aws_lb_target_group.target-groups["foo-target-group"].arn]
    "bar.example.com" = ["3", aws_lb_target_group.target-groups["bar-target-group"].arn]
  }

  listener_arn = aws_lb_listener.https_listener.arn
  priority     = each.value[0]

  action {
    type = "forward"
    target_group_arn = each.value[1]
  }

  condition {
    host_header {
      values = [each.key]
    }
  }

  tags = {
    Name = each.key
  }

}

 

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