AWS CloudFormation Application Load Balancer - how to redirect HTTP listener to HTTPS listener?

Viewed 14929

I am trying to write a CloudFormation template for ALB, but got stuck on the point where I would like to redirect ALB's HTTP listener's traffic to HTTPS listener. Docs mention only forwarding/redirection to the target group.

I am aware that it is achievable using the web interface (AWS Console), which I want to avoid. Also handling it on the server is a no go for me.

Is this ALB's feature simply not implemented in CloudFormation, but exists in Console?

4 Answers

On November 19, 2018 Amazon introduced the RedirectConfig for the Elastic Load Balancer Listener. This listener type is also used for the Application Load Balancer (ALB).

Below you find an example configuration for the usual HTTP to HTTPS redirect. Replace 'PublicLoadBalancerBackend' with your load balancers CloudFormation object.

  PublicLoadBalancerHttpRedirectListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    DependsOn:
      - PublicLoadBalancerBackend
    Properties:
      DefaultActions:
        - RedirectConfig:
            Host: "#{host}"
            Path: "/#{path}"
            Port: 443
            Protocol: "HTTPS"
            Query: "#{query}"
            StatusCode: HTTP_301
          Type: redirect
      LoadBalancerArn: !Ref 'PublicLoadBalancerBackend'
      Port: 80
      Protocol: HTTP

CloudFormation Documentation on the RedirectConfig: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listener-redirectconfig.html

CloudFormation Documentation on the Listener Action: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listener-defaultactions.html

Looks like for now the only option is to write a custom resource to manage it. See: https://github.com/jheller/alb-rule for a solid example to either implement - or use as a base for your own implementation. (I have no affiliation with the above code - just found for my own need to do the exact same thing)

It turns out that redirect is not implemented in CF as of now, what, sadly, is to be expected from AWS - source.

Related