Monday, January 31, 2022

[SOLVED] Unable to attach EC2 instance to a classic load balancer in AWS CDK

Issue

I have created an EC2 instance and a Classic Load Balancer in AWS CDK using typescript. But I'm unable to add that EC2 instance directly to that Load balancer.

this.Instance= new ec2.Instance(this, 'my-Instance', {
  vpc,
  instanceType: new InstanceType(instanceType),
  ...});

and load Balancer

this.Elb = new LoadBalancer(this, 'my-ELB', {
..
crossZone: true,
internetFacing: false,
...});

I'm looking to add this ec2 instance to this load balancer using something like this:

this.Elb.addEc2Instance(this.Instance)

but there isn't any such property available.


Solution

This finally worked for me. Putting it here so that no one else wastes as much time as I did in figuring this out.

elbObj.instances expects a string array of instance IDs. (read here)

 const elbObj = this.elb.node.defaultChild as CfnLoadBalancer;
    if (elbObj) {
      elbObj.instances = [(this.jenkinsInstance.instanceId).toString()];
    }


Answered By - Deepanshu Kalra
Answer Checked By - Timothy Miller (WPSolving Admin)