AWS – How to Tag EC2 Instances Spawned by ECS in Terraform

amazon-ecsamazon-web-servicesterraform

I have an ECS service that spawns some containers:

resource "aws_ecs_service" "rocketchat" {
  name            = "rocketchat-ecs-service"
  cluster         = "${aws_ecs_cluster.rocketchat.id}"
  task_definition = "${aws_ecs_task_definition.rocketchat.arn}"
  desired_count   = 2
  iam_role        = "${aws_iam_role.ecs_service.name}"
...

But the EC2 instances it creates have no 'Name' tag. I thought that name_prefix was what I was looking for, but it doesn't work:

resource "aws_launch_configuration" "rocketchat" {
  security_groups             = ["${aws_security_group.instance_sg.id}"]
  name_prefix                 = "${var.project_prefix}-rocketchat-"
  key_name                    = "${aws_key_pair.circles_rocketchat.key_name}"
...

The task definition for this container also has a name field, which doesn't work either:

[
  {
    "name": "rocketchat",
    "cpu": 256,
    "essential": true,
...

Amazon docs say here that 'tagging on creation' is not supported 'Launch template' but I am not sure that is exactly relevant; esp when you take my other ECS service on the same cluster, which doesn't have a load balancer, and therefore has no launch configuration.

EDIT:

@B.Miller s suggestion below has not tagged the actual instances but it does show in the console under EC2 > Auto Scaling Groups > Tags


+-------------+---------------------+-------------------+
| Key | Value | Tag New Instances |
+-------------+---------------------+-------------------+
| Environment | dev | Yes |
+-------------+---------------------+-------------------+
| Name | rocketchat-instance | Yes |
+-------------+---------------------+-------------------+

Best Answer

name_prefix creates a randomly unique name for the launch configuration using the prefix, not prefixs the things launched with it. name in a task definition is the name of the task definition itself. Because you are using a launch configuration I assume you are using an autoscaling group. Autoscaling groups allow you to set tags then propagate those tags.

For example you can specify individual tags and have them propogate:

resource "aws_autoscaling_group" "default" {
  ...
  tags = [
    {
      key                 = "explicit1"
      value               = "value1"
      propagate_at_launch = true
    },
    {
      key                 = "explicit2"
      value               = "value2"
      propagate_at_launch = true
    },
  ]
  ...
}

Edit: note that this works with the ECS-Optimised Amazon AMI but not CoreOS.