Deepanshu Kalra
Deepanshu Kalra

Reputation: 469

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

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.

Upvotes: 1

Views: 350

Answers (2)

Deepanshu Kalra
Deepanshu Kalra

Reputation: 469

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()];
    }

Upvotes: 1

Marcin
Marcin

Reputation: 238687

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,
});

Upvotes: 1

Related Questions