Dynamic naming for AWS EC2 instances launched by Terraform aws_autoscaling_group

One hack to do this is to pass the user-data script to the instance or autoscaling-group. PFB the link to the answer to a similar question.

https://stackoverflow.com/a/44613778/3304632


AWS autoscaling groups can be tagged as with many resources and using the propagate_at_launch flag those tags will also be passed to the instances that it creates.

Unfortunately these are entirely static and the ASG itself has no way of tagging instances differently. On top of this the default scale in policy will not remove the newest instances first so even if you did tag your instances as Node1, Node2, Node3 then when the autoscaling group scaled in it's most likely (depending on criteria) to remove Node1 leaving you with Node2 and Node3. While it's possible to change the termination policy to NewestInstance so that it would remove Node3 this is unlikely to be an optimal scale in policy.

I'd question why you feel you need to take ASG instances differently from each other and maybe rethink about how you manage your instances when they are more ephemeral as is generally the case in modern clouds but more so when using autoscaling groups.

If you really did want to tag instances differently for some specific reason you could have the ASG not propagate the Name tag at launch to instances and then have a Lambda function trigger on the scale out event (either via a lifecycle hook or a Cloudwatch event) to determine the tag value to use and then tag the instance with it.