AWS EC2 instance name is hyphenated

723 Views Asked by At

I am using the following terraform to create windows EC2 instance. The instance is launched successfully, but in AWS console I see hyphenated name for EC2 instance.
For brevity purpose I have removed some TF code

enter image description here

resource "aws_launch_template" "server_launch_template" {  
  name          = "my-launch-template"
  image_id      = "my-windows-ami-id"
  instance_type = "t3.medium"
  key_name      = "my-keypair"

  vpc_security_group_ids = [var.security_group_id]  

  iam_instance_profile {
    arn = aws_iam_instance_profile.my_instance.arn
  }   

  tag_specifications {
    resource_type = "instance"
    tags          = module.tags.mytags
  }

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_autoscaling_group" "server_autoscaling_group" {  
  name                      = "my autoscaling group"
  max_size                  = 1
  min_size                  = 1
  desired_capacity          = 1
  vpc_zone_identifier       = [var.subnet_id]
  wait_for_capacity_timeout = var.wait_for_capacity

  health_check_type = "EC2"

  dynamic "tag" {
    #some code here
  }

  launch_template {
    id      = aws_launch_template.server_launch_template.id
    version = "$Latest"
  }

  lifecycle {
    create_before_destroy = true
  }  
}

How and where do I specify instance name in the launch template?

2

There are 2 best solutions below

9
Paolo On

You can't define dynamic names for instances launched by an autoscaling group.

You can however configure a lambda function to run whenever the autoscaling launches new instances, and you can name the instances from the lambda.

1
LP13 On

This works. As @MarkoE suggested added Name tag in tag_specifications

resource "aws_launch_template" "server_launch_template" {  
  name          = "my-launch-template"
  image_id      = "my-windows-ami-id"
  instance_type = "t3.medium"
  key_name      = "my-keypair"

  vpc_security_group_ids = [var.security_group_id]  

  iam_instance_profile {
    arn = aws_iam_instance_profile.my_instance.arn
  }   

  tag_specifications {
    resource_type = "instance"
    tags          = merge(module.tags.mytags, { Name = "my-runner-instance" })
  }

  lifecycle {
    create_before_destroy = true
  }
}