How do I assign a ALB to the NLB Target group using cdk? Here is my code, everything works great and deploys no issue, the only thing is that I have to manually in the aws console assign the target for the NLB Target Group which I was able to define for ALB use.
Here is my code and I put a comment in the NLBTargetGroup where I would expect to be able to assign the ALB however it does not build/deploy when I do that.
const vpc = new ec2.Vpc($this, `BackendVpc-${stage}`, {
ip_addresses: ec2.IpAddresses.cidr('10.0.0.0/16'),
enableDnsSupport: true,
subnetConfiguration: [
{
cidrMask: 24,
name: 'private',
subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
},
{
cidrMask: 24,
name: 'public',
subnetType: ec2.SubnetType.PUBLIC,
}
],
} as ec2.VpcProps);
configVPC(vpc);
const cluster = new ecs.Cluster($this, `BackendCluster-${stage}`, { vpc: vpc, enableFargateCapacityProviders: true });
const imageRepo = new ecr.Repository($this, `BackendRepo-${stage}`, {
repositoryName: `backend-repo-${stage}`
});
const dockerImage = new DockerImageAsset($this,`DockerImage-${stage}`,{
directory: path.join(__dirname, '..', '..', 'backend'),
});
const deployment = new ECRDeployment($this, `DeployDockerImage-${stage}`, {
src: new DockerImageName(dockerImage.imageUri),
dest: new DockerImageName(`${imageRepo.repositoryUri}:latest`),
});
dockerImage.node.addDependency(imageRepo);
deployment.node.addDependency(imageRepo);
const service = new ApplicationLoadBalancedFargateService($this, `BackendService-${stage}`, {
serviceName: `BackendService-${stage}`,
cluster: cluster,
cpu: 256,
memoryLimitMiB: 2048,
taskImageOptions: {
image: ecs.ContainerImage.fromEcrRepository(imageRepo, 'latest'),
containerName: `backend-repo-${stage}`,
containerPort: 80,
environment: {
PORT: "80",
STAGE: stage,
AWS_DEFAULT_REGION: props?.env?.region || "",
USERPOOLID: userPool.userPoolId,
}
},
desiredCount: 1,
publicLoadBalancer: false,
});
const nlb = new NetworkLoadBalancer($this, `BackendNLB-${stage}`, {
vpc: vpc,
crossZoneEnabled: true,
internetFacing: false,
vpcSubnets: {
subnets: vpc.privateSubnets
}
});
const nlbListener = nlb.addListener(`BackendNLBListener-${stage}`, {
port: 80,
});
const nlbTargetGroup = new NetworkTargetGroup($this, `BackendNLBTargetGroup-${stage}`, {
port: 80,
vpc: vpc,
targetType: TargetType.ALB,
// here I would expect to set the target to my ALB
// target: [service.loadBalancer]
// but I get the following error
// Property 'attachToNetworkTargetGroup' is missing in type 'ApplicationLoadBalancer' but required in type 'INetworkLoadBalancerTarget'.
});
nlbListener.addTargetGroups(`BackendNLBAddingTargetGroup-${stage}`, nlbTargetGroup);
The
targetsprop of theNetworkTargetGroupexpects aINetworkLoadBalancerTarget. When you go to its documentation, it contains the list of classes that implement this interface. Among them isAlbTarget.You do not have to specify the
targetTypeprop, it is determined automatically.