我如何通过 Instance-name 获取现有的 EC2 实例,并在 Python 中使用 AWS CDK 将它们作为目标添加到 ALB

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

如何通过实例名称获取现有的 EC2 实例,并使用 AWS CDK 在 Python 中将它们作为目标添加到 ALB。 请在下面找到我的示例代码使用 AWS-CDK-Python 语言

创建一个 ALB
    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```

我不确定如何使用 CDK 执行此操作,但通常您可以使用 register_targets() 命令:

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.

使用 CDK 提供的 InstanceTarget 方法,我们可以获取 EC2 实例详细信息并存储在一个对象中;在 cdk 模块中使用 add_targets 方法时,我可以提供存储 ec2 实例详细信息的对象。