简体   繁体   English

Terraform 是否公开 ECS 启动类型中使用的 EC2 实例的实例 ID?

[英]Does Terraform expose the instance ID for an EC2 instance used in an ECS launch type?

I'm deploying an app to an ECS cluster with an EC2 launch type.我正在使用 EC2 启动类型将应用程序部署到 ECS 集群。 I've had some success here, and have stood up a load balancer in front of the cluster, and the instance receives and responds to traffic fine.我在这里取得了一些成功,并且在集群前面建立了一个负载均衡器,并且该实例可以很好地接收和响应流量。

For a separate task, I'm also looking at being able to individually address the instance, which Terraform lets me do if I've got the instance ID, but I don't see the instance ID being one of the data outputs of aws_launch_configuration .对于一个单独的任务,我也在考虑能够单独处理实例,如果我有实例 ID,Terraform 可以让我这样做,但我没有看到实例 ID 是aws_launch_configuration的数据输出之一.

Is there a way to extract the instance ID of an EC2 instance used in an ECS cluster?有没有办法提取ECS集群中使用的EC2实例的实例ID?

You can do this by using the aws_instance data source您可以使用aws_instance数据源来执行此操作

In it, you can specify a few filters to retrieve any EC2 instance.在其中,您可以指定一些过滤器来检索任何 EC2 实例。

For example, let's say that your launch configuration (by the way, you should use a launch template, it's "launch configuration v2" basically with more features) assigns some tags to your ECS Container Instance, one of them being Name:ECSClusterX .例如,假设您的启动配置(顺便说一句,您应该使用启动模板,它基本上是具有更多功能的“启动配置 v2”)为您的 ECS 容器实例分配了一些标签,其中之一是Name:ECSClusterX Knowing this you can retrieve the said EC2 instance by:知道这一点后,您可以通过以下方式检索所述 EC2 实例:

data "aws_instance" "ecs-instance" {
  filter {
    name   = "tag:Name"
    values = ["ECSClusterX"]
  }
}

then you can retrieve the id of the found instance, by: aws_instance.ecs-instance.id .然后您可以通过以下方式检索找到的实例的 ID: aws_instance.ecs-instance.id

That's it, you are all set!就是这样,你已经准备好了!

If you are looking for launch a task in a specific instances, a good practice is using attributes.如果您正在寻找在特定实例中启动任务,一个好的做法是使用属性。

In your cluster, move to the ECS Instances tab, then select one instance.在您的集群中,移至ECS Instances选项卡,然后移至 select 一个实例。 Open the Actions menu like in the picture and go to View/Edit Attributes :打开图片中的操作菜单和 go 以查看/编辑属性

在此处输入图像描述

Add your attribute:添加您的属性: 在此处输入图像描述

The last step is to configure your task definition in your terraform.最后一步是在 terraform 中配置您的任务定义。

resource "aws_ecs_task_definition" "component1" {
    ...
    placement_constraints {
      type = "memberOf"
      expression =  "attribute:deploy_type == standard"
    }
    ...
}

Now the task only will be executed in the instances that match the attribute.现在任务只会在匹配属性的实例中执行。

I use lambda function to keep all the time at least one instance with the each attribute block that I need.我使用 lambda function 始终至少保留一个实例,其中包含我需要的每个属性块。 But you can integrate instances to the cluster with different launch templates and different attributes.但是您可以将实例集成到具有不同启动模板和不同属性的集群中。

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

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