I'm deploying an app to an ECS cluster with an EC2 launch type. 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
.
Is there a way to extract the instance ID of an EC2 instance used in an ECS cluster?
You can do this by using the aws_instance
data source
In it, you can specify a few filters to retrieve any EC2 instance.
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
. Knowing this you can retrieve the said EC2 instance by:
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
.
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. Open the Actions menu like in the picture and go to View/Edit Attributes :
The last step is to configure your task definition in your 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. But you can integrate instances to the cluster with different launch templates and different attributes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.