Search code examples
aws-cdk

CDK v2: nodejs how do I attach a ALB to a NLB targetgroup


I have this which is working to get an ALB type target group:

    const alb = elbv2.ApplicationLoadBalancer.fromLookup(this, 'vtocALB', {
      loadBalancerArn: "arn:aws:elasticloadbalancing:us-west-2:111111:loadbalancer/app/xxxx-alb/8eefa0843c6b512f"
    });


    // Lookup a VPC by its name
    const vpc = ec2.Vpc.fromLookup(this, 'nameHere', {
      vpcName: 'Name',
    });

    // creating an internal NLB to point the api-gws via vpc-link
    const nlb = new elbv2.NetworkLoadBalancer(this, 'AuthNLB', {
      vpc,
      internetFacing: false, 
    });
    const tg = new elbv2.NetworkTargetGroup(this, 'AuthTGAlb', {
      port: 443,
      protocol: elbv2.Protocol.TCP,
      vpc: vpc,
      targetType: elbv2.TargetType.ALB,
      
    });
    const listener = nlb.addListener('listener80', {
      port: 80,
      defaultTargetGroups: [tg],
    });

My issue is I can't seem to figure out how to set the ALB I lookup as the target in the NLB target group. It works fine if I attach it in the UI.


Solution

  • Because you didn't add your ALB to your target group. You need the target parameter here:

     const tg = new elbv2.NetworkTargetGroup(this, 'AuthTGAlb', {
      port: 443,
      protocol: elbv2.Protocol.TCP,
      vpc: vpc,
      targetType: elbv2.TargetType.ALB,
      
      // Add your target
      target: [alb]
    });
    

    https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_elasticloadbalancingv2.NetworkTargetGroup.html