I have successfully created an autoscaling group using Terraform. I would like to now find a way to dynamically name the provisioned instances based on index value.
For an aws_instance
type, it can be easily done by:
resource "aws_instance" "bar" {
count = 3
tags {
Name = "${var.instance_name_gridNode}${count.index + 1}"
App-code = "${var.app-code}"
PC-code = "${var.pc-code}"
}
}
This will result in 3 instances named:
1) Node1
2) Node2
3) Node3
However as aws_autoscaling_group
is dynamically provisioned (for both scaling in and out situations) how does one control the naming convention of the provisioned instances?
resource "aws_autoscaling_group" "gridrouter_asg" {
name = "mygridrouter"
launch_configuration = "${aws_launch_configuration.gridGgr_lcfg.id}"
min_size = 1
max_size = 2
health_check_grace_period = 150
desired_capacity = 1
vpc_zone_identifier = ["${var.subnet_id}"]
health_check_type = "EC2"
tags = [
{
key = "Name"
value = "${var.instance_name_gridGgr_auto}"
propagate_at_launch = true
},
]
}
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With