Search code examples
terraformelastic-load-balancer

Terraform (A)lb redirect http -> https


If I get this right, lb_listener only accepts forward as valid action type. https://www.terraform.io/docs/providers/aws/r/lb_listener.html How do I configure a listener to redirect HTTP to HTTPS?

i.e. this is the desired state in elb listener:

enter image description here


Solution

  • This functionality was added to the AWS provider and released with 1.33.0.

    Here's how you'd set the default action on a load balancer listener with the aws_lb_listener resource:

    resource "aws_lb" "front_end" {
      # ...
    }
    
    resource "aws_lb_listener" "front_end" {
      load_balancer_arn = "${aws_lb.front_end.arn}"
      port              = "80"
      protocol          = "HTTP"
    
      default_action {
        type = "redirect"
    
        redirect {
          port        = "443"
          protocol    = "HTTPS"
          status_code = "HTTP_301"
        }
      }
    }
    

    You can also add redirects and fixed type responses with individual load balancer listener rules in the aws_lb_listener_rule resource:

    resource "aws_lb_listener_rule" "redirect_http_to_https" {
      listener_arn = "${aws_lb_listener.front_end.arn}"
    
      action {
        type = "redirect"
    
        redirect {
          port        = "443"
          protocol    = "HTTPS"
          status_code = "HTTP_301"
        }
      }
    
      condition {
        host_header {
          values = ["my-service.*.terraform.io"]
        }
      }
    }