Load Balancing

The resource type “aws_elb” creates Elastic Load Balancer resource, also known as a “Classic Load Balancer”.

The resource type “aws_lb” (aws_alb functionality is identical) creates Application Load Balancer/Network Load Balancer.

To create an Elastic Load Balancer,

  • availability_zones
  • instance_port
  • instance_protocol
  • lb_port
  • lb_protocol
  • healthy_threshold
  • unhealthy_threshold
  • target
  • interval
  • timeout are mandatory arguments.
resource "aws_elb" "test_elb" {
  name = "test-elb"
  availability_zones = ["us-east-1a", "us-east-1b", "us-east-1c"]
  listener {
    instance_port = 8000
    instance_protocol = "http"
    lb_port = 80
    lb_protocol = "http"
  }
  listener {
    instance_port = 8000
    instance_protocol = "http"
    lb_port = 443
    lb_protocol = "https"
    ssl_certificate_id = "arn:aws:iam::123456789012:server-certificate/certName"
  }
  health_check {
    healthy_threshold = 2
    unhealthy_threshold = 2
    timeout = 3
    target = "HTTP:8000/"
    interval = 30
  }
  instances = ["${aws_instance.webserver.id}"]
  cross_zone_load_balancing = true
  idle_timeout = 400
  connection_draining = true
  connection_draining_timeout = 400
}

Application Load Balancer

resource "aws_lb" "test" {
  name = "test-lb-tf"
  internal = false
  load_balancer_type = "application"
  security_groups = ["${aws_security_group.lb_sg.id}"]
  subnets = ["${aws_subnet.public.*.id}"]
  enable_deletion_protection = true
  access_logs {
    bucket = "${aws_s3_bucket.lb_logs.bucket}"
    prefix = "test-lb"
    enabled = true
  }
}

Network Load Balancer

resource "aws_lb" "test" {
  name = "test-lb-tf"
  internal = false
  load_balancer_type = "network"
  subnets = ["${aws_subnet.public.*.id}"]
  enable_deletion_protection = true
}

Target Group and Lister for Application/Network Load Balancer

resource "aws_alb_target_group" "test_target_group" {
  name="test-target-group"
  port="80"
  protocol="HTTP"
  vpc_id="${aws_vpc.ecs_vpc.id}"
  health_check {
    healthy_threshold="3"
    unhealthy_threshold="2"
    interval="30"
    matcher="200"
    path="/"
    port="traffic-port"
    protocol="HTTP"
    timeout="5"
  }
  depends_on= ["aws_alb.test_load_balancer"]
}
resource "aws_alb_listener" "alb_listener" {
  load_balancer_arn="${aws_alb.test_load_balancer.arn}"
  port="80"
  protocol="HTTP"
  default_action {
    target_group_arn="${aws_alb_target_group.test_target_group.arn}"
    type="forward"
  }
}
Advertisements