0

How can I fetch existing EC2 Instances via Instance-name and add them as targets to ALB using AWS CDK in Python. Please find my sample code below to create an ALB using AWS-CDK-Python Language

    core,
    aws_ec2,
    aws_elasticloadbalancingv2,
)

class WebsiteStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        self.vpc = aws_ec2.Vpc.from_lookup(self, 'default_vpc', is_default=True)

        self.sg_ssh = aws_ec2.SecurityGroup(
            self,
            'ssh',
            vpc=self.vpc,
            description="Allow SSH from anywhere",
            security_group_name="SSH from anywhere"
        )
        self.sg_ssh.add_ingress_rule(aws_ec2.Peer.any_ipv4(), aws_ec2.Port.tcp(22))

        tg = aws_elasticloadbalancingv2.ApplicationTargetGroup(
            self,
            'website-target-group',
            protocol=aws_elasticloadbalancingv2.ApplicationProtocol.HTTP,
            port=80,
            vpc=self.vpc,
            # target_type=aws_elasticloadbalancingv2.TargetType.INSTANCE,
            # targets=[ec2],  # FIXME
        )
        tg.add_target(ec2)  # FIXME```
fedonev
  • 20,327
  • 2
  • 25
  • 34

2 Answers2

0

I'm not sure how to do it using the CDK, but normally you could use the register_targets() command:

Registers the specified targets with the specified target group.

If the target is an EC2 instance, it must be in the running state when you register it.

By default, the load balancer routes requests to registered targets using the protocol and port for the target group. Alternatively, you can override the port for a target when you register it. You can register each EC2 instance or IP address with the same target group multiple times using different ports.

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
0

Using InstanceTarget method available from CDK we can fetch EC2 Instance details and store in an object; while using add_targets method in cdk module I can provide the object in which ec2 instance details were stored.

  • why is this marked as the answer, he provides no information regarding pulling the actual EC2 by the name in the cdk. – user2612665 May 17 '23 at 23:05