简体   繁体   English

如何通过 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

How can I fetch existing EC2 Instances via Instance-name and add them as targets to ALB using AWS CDK in Python.如何通过 Instance-name 获取现有 EC2 实例并使用 Python 中的 AWS CDK 将它们作为目标添加到 ALB。 Please find my sample code below to create an ALB using AWS-CDK-Python Language请在下面找到我的示例代码以使用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```

I'm not sure how to do it using the CDK, but normally you could use the register_targets() command:我不确定如何使用 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.如果目标是 EC2 实例,则注册时它必须在running的 state 中。

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.您可以使用不同的端口向同一目标组多次注册每个 EC2 实例或 IP 地址。

Using InstanceTarget method available from CDK we can fetch EC2 Instance details and store in an object;使用 CDK 提供的 InstanceTarget 方法,我们可以获取 EC2 实例详细信息并存储在 object 中; while using add_targets method in cdk module I can provide the object in which ec2 instance details were stored.在 cdk 模块中使用 add_targets 方法时,我可以提供存储 ec2 实例详细信息的 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM