Search code examples
amazon-web-servicesaws-cdkclouddevelopmentkit

How can I fetch existing EC2 Instances via Instance-name and add them as targets to ALB using AWS CDK in Python


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```

Solution

  • 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.