Manuel Lara Caro
Manuel Lara Caro

Reputation: 51

Set a unique tag to each instance of Terraform aws_autoscaling_group module

is possible to assign a different tag value to each EC2 instance created by the aws_autoscaling_group module of Terraform. For example, node1, node2, node3 and node4 for a ASG of 4 instances.

thanks.

Upvotes: 4

Views: 6677

Answers (1)

ydaetskcoR
ydaetskcoR

Reputation: 56877

Autoscaling groups in AWS can only (optionally) propagate the tags of the ASG to the instances it creates. It can't do any dynamic tagging based on the count of instances in the ASG.

If you really need this then you'd have to have the user data of the instances perform some step that calculates what the name tag should be and then retags itself (of course the instance would have to have the relevant IAM permissions for this).

For an instance to work out what number it is in an ASG might be tricky (consider if your autoscaling action adds multiple instances at the same time or quickly enough that some may not have retagged themselves before another is created) but you could more easily get it to find its own instance Id and use that to create a unique tagged name if that's more what you want.

Something like this might be useful in that case:

ID=$(curl http://169.254.169.254/latest/meta-data/instance-id)
CURRENT_NAME=$(aws ec2 describe-tags --filters Name=resource-id,Values=${ID} Name=key,Values=Name --query Tags[].Value --output text
NEW_NAME=${CURRENT_NAME}-${ID}

aws ec2 create-tags --resources ${ID} --tags Key=Name,Value=${NEW_NAME}

Upvotes: 3

Related Questions