[SOLVED] How to deploy AWS loadbalancer listeners via AWS CDK that redirect and forward to ECS container

Issue

This Content is from Stack Overflow. Question asked by user7186882

I’m trying to deploy a listener on a loadbalancer with the following configuration (manually modified and tested, following CDK deploy):

Listner Configuration

The following code adds the listener, but doesn’t update listener to redirect port 80 to 443 (https) and the HTTPs:443 listener ID is trying to connect with ECS over HTTPS rather than HTTP.

    loadbalancer = cdk.aws_elasticloadbalancingv2.ApplicationLoadBalancer(
        self, 'loadbalancer',
        vpc=p_vpc,
        internet_facing=True,
        load_balancer_name='ppal-alb'
    )

    loadbalancer_listener = cdk.aws_elasticloadbalancingv2.ApplicationListener(
        self, 'loadbalancer-listener',
        open=True,
        port=443,
        certificates=[p_certificate],
        load_balancer=loadbalancer
    )

    loadbalancer_listener.add_action(
        'redirect-action',
        action=cdk.aws_elasticloadbalancingv2.ListenerAction
        .redirect(
            port='443',
            protocol='HTTPS',
            permanent=True)
    )

    target_group_config = cdk.aws_elasticloadbalancingv2.ApplicationTargetGroup(
        self, 'target-group',
        port=443,
        protocol=cdk.aws_elasticloadbalancingv2.ApplicationProtocol.HTTPS,
        target_type=cdk.aws_elasticloadbalancingv2.TargetType.IP,
        vpc=p_vpc
    )

    loadbalancer_listener.add_target_groups(
        'loadbalancer_listener_target_group',
        target_groups=[target_group_config]
    )



Solution

I was using ApplicationLoadBalancedFargateService which I hadn’t realized automatically added the http listener, so the above action that I had was having no effect.

Turns out this pattern is useful for getting up and running, but removes the fine grained control. The desired behavior is still possible with ApplicationLoadBalancedFargateService you just need to add the following options:

redirect_http=True,          
protocol=cdk.aws_elasticloadbalancingv2.ApplicationProtocol.HTTPS,
certificate=req_certificate,
domain_name="my_domain_name.com",
domain_zone=cdk.aws_route53.HostedZone.from_lookup(self, f"{id}-hosted-zone", domain_name="my_domain_name.com")

This will:

  • redirect http to https on the ALB
  • forward traffic from https on the ALB to port 80 on the fargate service
  • add the A name alias in route53 for the domain


This Question was asked in StackOverflow by user7186882 and Answered by user7186882 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?