This is what I am trying to do. I have 2 auto scaling groups created with Terraform. One is starting 3 EC2 instances in three different availability zones, with public IP addresses. The other auto scaling group is starting 3 EC2 instances in three different availability zones, with private IP addresses I am trying to set up a unique "Name" tag for each instance. In Terraform, I see the auto scaling resource has a tag block, but at apply the same tag is applied to all 3 instances. Also, I tried setting up my code to where one auto scaling group can launch all my instances (both public & private), but am having trouble looping with the 'for' expression in my vpc_zone_identifier statement. This issue is forcing me to create a second auto scaling group for the private instances. Any advice would be helpful in combining these auto scaling groups and how to tag each instance with a unique tag.
resource "aws_autoscaling_group" "public" {
name = "${var.main_as}-Public"
launch_configuration = aws_launch_configuration.main.id
vpc_zone_identifier = [
for subnet in aws_subnet.public : subnet.id
]
min_size = 3
max_size = 3
}
resource "aws_autoscaling_group" "private" {
name = "${var.main_as}-Private"
launch_configuration = aws_launch_configuration.main.id
vpc_zone_identifier = [
for subnet in aws_subnet.private : subnet.id
]
min_size = 3
max_size = 3
}
With an autoscaling group you should not be trying to generate unique names for all instances, in fact this leads into the methodology of pets vs cattle. By naming resources they become precious and can lead into designs whereby you have a single point of failure.
In practice this can be hard for certain realms (such as Databases) but you should try to build your architecture to be immutable especially in an autoscaling group whereby instances can be replaced (even if you have a min and max the same size, any underlying host failures will launch a new instance to replace).
By having your infrastructure being immutable your architecture will be more resilient to unknown events and will enforce best practices for server builds.
If you need an identifier for the instance, rather than using the tag I would recommend using the instance ID as this will always be unique for your hosts.
Otherwise if you want to still use an Autoscaling group with unique name tags for the hosts you will need to create an event for during the launch of the host. This would then need trigger a Lambda which would programmatically update the EC2 instance and assign it a unique name.