aws-cdk icon indicating copy to clipboard operation
aws-cdk copied to clipboard

(aws-elasticloadbalancingv2): Cannot use a single application load balancer as a target for the network load balancer

Open matsaune opened this issue 5 years ago • 14 comments

What is the problem?

I am trying to use a single application load balancer as a target for the network load balancer and I am defining this in CDK. Whenever I try to deploy this I get an errorMsg and the stack fails to deploy

Reproduction Steps

Use the example code on https://docs.aws.amazon.com/cdk/api/latest/docs/aws-elasticloadbalancingv2-readme.html#using-application-load-balancer-targets in a stack.

This is my code (adjusted example from above) that fails:

import * as cdk from '@aws-cdk/core';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as iam from "@aws-cdk/aws-iam";
import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2';
import * as targets from '@aws-cdk/aws-elasticloadbalancingv2-targets';
import * as ecs from '@aws-cdk/aws-ecs';
import * as patterns from '@aws-cdk/aws-ecs-patterns';

/**
 * Test Nbl to Alb CDK
 */
export class NblToAlbStack extends cdk.Stack {
    constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
        super(scope, id, props);

        //This is required due to company policy
        const boundary = iam.ManagedPolicy.fromManagedPolicyName(this, 'Boundary', 'Core-PermissionBoundaryPolicy');
        iam.PermissionsBoundary.of(this).apply(boundary);

        //Get existing VPC
        const coreVpc = ec2.Vpc.fromLookup(this, 'CoreVPC',{isDefault: false,vpcName: 'core-vpc' });

        const task = new ecs.FargateTaskDefinition(this, 'Task', { cpu: 256, memoryLimitMiB: 512 });
        task.addContainer('nginx', {
            image: ecs.ContainerImage.fromRegistry('public.ecr.aws/nginx/nginx:latest'),
            portMappings: [{ containerPort: 80 }],
        });

        const svc = new patterns.ApplicationLoadBalancedFargateService(this, 'Service', {
            vpc: coreVpc,
            taskDefinition: task,
            publicLoadBalancer: false,
        });

        const nlb = new elbv2.NetworkLoadBalancer(this, 'Nlb', {
            vpc:coreVpc,
            crossZoneEnabled: true,
            internetFacing: true,
        });

        const listener = nlb.addListener('listener', { port: 80 });
        const albTarget = new targets.AlbTarget(svc.loadBalancer, 80);

        listener.addTargets('Targets', {
            targets: [albTarget],
            port: 80,
        });

        new cdk.CfnOutput(this, 'NlbEndpoint', { value: `http://${nlb.loadBalancerDnsName}`})

    }
}

What did you expect to happen?

I expected stack to de deployed OK.

What actually happened?

Failed resources:
 10:37:47 AM | CREATE_FAILED        | AWS::ElasticLoadBalancingV2::TargetGroup  | Nlb/listener/TargetsGroup (NlblistenerTargetsGroupDD2A3CB0) If the target type is ALB, the target must have at least one listener that matches the target group port or any specified port overrides (Service: AmazonElasticLoadBalancing; Status Code: 400; Error Code: ValidationError; Request ID: 671fe9d5-e9af-4652-aee7-467e682fcdfa; Proxy: null)
        new TargetGroupBase (/Users/ad03490/projects/bitbucket/cdk-document-converter/node_modules/@aws-cdk/aws-elasticloadbalancingv2/lib/shared/base-target-group.ts:129:21)
        \_ new NetworkTargetGroup (/Users/ad03490/projects/bitbucket/cdk-document-converter/node_modules/@aws-cdk/aws-elasticloadbalancingv2/lib/nlb/network-target-group.ts:49:5)
        \_ NetworkListener.addTargets (/Users/ad03490/projects/bitbucket/cdk-document-converter/node_modules/@aws-cdk/aws-elasticloadbalancingv2/lib/nlb/network-listener.ts:160:19)
        \_ new NblToAlbStack (/Users/ad03490/projects/bitbucket/cdk-document-converter/lib/nbl-to-alb-stack.ts:42:18)
        \_ Object.<anonymous> (/Users/ad03490/projects/bitbucket/cdk-document-converter/bin/cdk-document-converter.ts:23:23)
        \_ Module._compile (node:internal/modules/cjs/loader:1095:14)
        \_ Module.m._compile (/Users/ad03490/projects/bitbucket/cdk-document-converter/node_modules/ts-node/src/index.ts:1056:23)
        \_ Module._extensions..js (node:internal/modules/cjs/loader:1124:10)
        \_ Object.require.extensions.<computed> [as .ts] (/Users/ad03490/projects/bitbucket/cdk-document-converter/node_modules/ts-node/src/index.ts:1059:12)
        \_ Module.load (node:internal/modules/cjs/loader:975:32)
        \_ Function.Module._load (node:internal/modules/cjs/loader:816:12)
        \_ Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
        \_ main (/Users/ad03490/projects/bitbucket/cdk-document-converter/node_modules/ts-node/src/bin.ts:198:14)
        \_ Object.<anonymous> (/Users/ad03490/projects/bitbucket/cdk-document-converter/node_modules/ts-node/src/bin.ts:288:3)
        \_ Module._compile (node:internal/modules/cjs/loader:1095:14)
        \_ Object.Module._extensions..js (node:internal/modules/cjs/loader:1124:10)
        \_ Module.load (node:internal/modules/cjs/loader:975:32)
        \_ Function.Module._load (node:internal/modules/cjs/loader:816:12)
        \_ Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
        \_ node:internal/main/run_main_module:17:47

 ❌  NblToAlbStack failed: Error: The stack named NblToAlbStack failed creation, it may need to be manually deleted from the AWS console: ROLLBACK_COMPLETE
    at Object.waitForStackDeploy (/usr/local/lib/node_modules/aws-cdk/lib/api/util/cloudformation.ts:305:11)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at prepareAndExecuteChangeSet (/usr/local/lib/node_modules/aws-cdk/lib/api/deploy-stack.ts:352:26)
    at CdkToolkit.deploy (/usr/local/lib/node_modules/aws-cdk/lib/cdk-toolkit.ts:189:24)
    at initCommandLine (/usr/local/lib/node_modules/aws-cdk/bin/cdk.ts:225:9)
The stack named NblToAlbStack failed creation, it may need to be manually deleted from the AWS console: ROLLBACK_COMPLETE
Error: The stack named NblToAlbStack failed creation, it may need to be manually deleted from the AWS console: ROLLBACK_COMPLETE
    at Object.waitForStackDeploy (/usr/local/lib/node_modules/aws-cdk/lib/api/util/cloudformation.ts:305:11)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at prepareAndExecuteChangeSet (/usr/local/lib/node_modules/aws-cdk/lib/api/deploy-stack.ts:352:26)
    at CdkToolkit.deploy (/usr/local/lib/node_modules/aws-cdk/lib/cdk-toolkit.ts:189:24)
    at initCommandLine (/usr/local/lib/node_modules/aws-cdk/bin/cdk.ts:225:9)

CDK CLI Version

1.127.0 (build 0ea309a)

Framework Version

No response

Node.js Version

v16.4.2

OS

System Version: macOS 11.5.2 (20G95) Kernel Version: Darwin 20.6.0

Language

Typescript

Language Version

Typescript Version 3.9.10

Other information

No response

matsaune avatar Oct 28 '21 09:10 matsaune

We had the same (intermittent) issue in one of our stacks. It depends on whether the ALB listener gets created first before the NLB - which I found can vary. The workaround is to add an explicit dependency onto the ALB listener and the NLB target group:

const svc = new patterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  // ...
});
const nlbTargetGroup = listener.addTargets('Targets', {
  targets: [new targets.AlbTarget(svc.loadBalancer, 80)],
  port: 80,
  healthCheck: {
    protocol: elbv2.Protocol.HTTP,
  },
});

nlbTargetGroup.node.addDependency(svc.listener);

jamesorlakin avatar Oct 31 '21 10:10 jamesorlakin

This is a open existing issue and needs to be resolved.

aritranagnordcloud avatar Feb 04 '22 12:02 aritranagnordcloud

I've just had the same issue.....

mrpackethead avatar Mar 22 '22 02:03 mrpackethead

I'm using yaml to describe resources and solved the same issue by moving my app load balancer description to the top of the file (before the network lb description). Also DependsOn may help

alekseystryukov avatar Nov 14 '22 13:11 alekseystryukov

I have the same issue with java code:

ApplicationLoadBalancedFargateService fargateService = createFargateService(stack);
NetworkListener listener = networkLoadBalancer.addListener("listener", 
BaseNetworkListenerProps.builder().port(5000).build());
listener.addTargets("alb fargate target", AddNetworkTargetsProps.builder()
                .targets(List.of(new AlbTarget(fargateService.getLoadBalancer(), 5000)))
                .port(5000)
                .build());

SiwyDym avatar Jan 12 '23 09:01 SiwyDym

This PR was abandoned, it seems like it could still be a suitable solution if anyone wants to pick it up from where it was left off https://github.com/aws/aws-cdk/pull/17248

peterwoodworth avatar Apr 28 '23 20:04 peterwoodworth

I've been trying to reproduce this on cdk 2.84 in various US regions and I haven't been able to do so in about 20 attempts.

jlscott3 avatar Jun 28 '23 02:06 jlscott3

CDK 2.92 I was able to reproduce the error in this commit, but I eventually fixed it by specifying the vpcSubnets for both the ALB and the NLB. My repo contains a working example here https://github.com/LajosPolya/aws-cdk-templates/tree/main/deploy-nlb-with-alb

I ran into a second issue though, when trying to destroy the environment it errors out because it tries to delete the ALB before deleting its target.

Error message: Listener port '80' is in use by registered target '<ALB Target ARN>' and cannot be removed

What's interesting about this is that the AWS Console allows me to delete the ALB without any issue. Then I can delete the stack without any issues.

Either way, I was able to solve my problem with the help of @jamesorlakin 's recommendation

LajosPolya avatar Aug 17 '23 01:08 LajosPolya

This PR is Good to Review https://github.com/aws/aws-cdk/pull/30396

stm29 avatar May 31 '24 13:05 stm29

@Leo10Gama , Where should I reach out to get my contribution reviewed by community?

stm29 avatar Jun 11 '24 05:06 stm29

Hi @stm29! Feel free to reach out on the cdk.dev Slack

Leo10Gama avatar Jun 11 '24 17:06 Leo10Gama

@Leo10Gama , I tried reaching out in both #aws-cdk and #contributing channel.

I am unable to find a community reviewer(trusted cdk reviewer).

It's been sitting here for more than 2 weeks without a review.

It would be more helpful if I am getting an initial review at least.

What would be the best way to take it forward.

stm29 avatar Jun 15 '24 15:06 stm29

Comments on closed issues and PRs are hard for our team to see. If you need help, please open a new issue that references this one.

github-actions[bot] avatar Aug 15 '24 18:08 github-actions[bot]

Comments on closed issues and PRs are hard for our team to see. If you need help, please open a new issue that references this one.

github-actions[bot] avatar Aug 15 '24 18:08 github-actions[bot]