1

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.

Deepanshu Kalra
  • 419
  • 2
  • 9
  • 23

2 Answers2

1

You can't do this with LoadBalancer. You have to place your instance in autoscaling group first. And then you attach the ASG to your LB as shown in the example:

const lb = new elb.LoadBalancer(this, 'LB', {
    vpc,
    internetFacing: true,
    healthCheck: {
        port: 80
    },
});

lb.addTarget(myAutoScalingGroup);
lb.addListener({
    externalPort: 80,
});
Marcin
  • 215,873
  • 14
  • 235
  • 294
1

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()];
    }
Deepanshu Kalra
  • 419
  • 2
  • 9
  • 23