HTTP/HTTPS
The following module creates an HTTPS load balancer using an ACM certificate and configured to redirect HTTP to HTTPS. Additional it expects the backends to provide a health check at /healthz that returns a 200 response.
variable "name" {}
variable "vpc_id" {}
variable "zone_id" {}
variable "security_group_id" {}
variable "domain" {}
variable "certificate_arn" {}
variable "port" {
default = 8080
}
variable "health" {
default = "/healthz"
}
data "aws_subnets" "public" {
filter {
name = "vpc-id"
values = [var.vpc_id]
}
tags = {
Tier = "Public"
}
}
resource "aws_lb" "main" {
name = var.name
internal = false
load_balancer_type = "application"
security_groups = [var.security_group_id]
subnets = data.aws_subnets.public.ids
}
resource "aws_lb_target_group" "main" {
name = var.name
port = var.port
protocol = "HTTP"
vpc_id = var.vpc_id
health_check {
path = var.health
matcher = "200"
healthy_threshold = 2
unhealthy_threshold = 2
interval = 30
timeout = 5
}
}
resource "aws_lb_listener" "http" {
load_balancer_arn = aws_lb.main.arn
port = "80"
protocol = "HTTP"
default_action {
type = "redirect"
redirect {
port = "443"
protocol = "HTTPS"
status_code = "HTTP_301"
}
}
}
resource "aws_lb_listener" "https" {
load_balancer_arn = aws_lb.main.arn
port = "443"
protocol = "HTTPS"
ssl_policy = "ELBSecurityPolicy-2016-08"
certificate_arn = var.certificate_arn
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.main.arn
}
}
resource "aws_route53_record" "alb_record" {
zone_id = var.zone_id
name = var.domain
type = "A"
alias {
name = aws_lb.main.dns_name
zone_id = aws_lb.main.zone_id
evaluate_target_health = true
}
}