I would like to get some sort of ordinal number for each instance in an auto-scaling group. Let's say that group have 5 instances maximum. I would like to have a number 0, 1, 2, 3, 4 or 1, 2, 3, 4, 5 assigned to each running member of that autoscaling group, and whenever one member is brought down, and another one started in its place, retain that number. Is this possible somehow?
-
Yes, its possible, but it requires a fully custom solution and code. – Marcin Apr 18 '23 at 23:09
-
Can I ask... _Why_ do you want this number? How will this number be used? – John Rotenstein Apr 19 '23 at 00:46
3 Answers
If multiple instances are launched at the same time, you can use the ami-launch-index
value from the EC2 Instance Metadata. This value is different for each instance launched.
This definitely works for instances launched with a Count
of multiple instances, but I'm not sure whether Auto Scaling would launch multiple instances this way when the Auto Scaling group is initially created.
However, the ami-launch-index
would definitely not work for subsequent instances launched by Auto Scaling because they would be individually launched.
In fact, attempting to assign a number of an Auto Scaling instance can be quite complex. For example, imagine this situation:
- There are 3 existing instances (0, 1, 2)
- Instance #1 is terminated (leaving 0 and 2)
- When a new instance is launched, should it be #1 or #3?
This would depend on whether you want each instance to have a "never used" number, or whether you just want each instance to have a "unique" number. If your goal is for a unique number, then you could simply use the Instance ID, which is guaranteed to be unique.
Worst-case, you could run a script from User Data that queries Auto Scaling to ask how many existing instances are in the Auto Scaling group, and what numbers are being used. The script could then select a number for itself and add it as a Tag on the instance so that the number is accessible outside the instance.

- 241,921
- 22
- 380
- 470
I actually have an intricate solution for this which involves an EFS volume where the various instances record their presence and negotiate their identities and other things.
The reason I had asked was that I did this for Unix servers, and now I needed it for Windows. Thought that if there is an easier way I should do that. Seems like there isn't.
But I did manage to access EFS from the Windows instance from the University of Michigan NFSv4.1 server. Using only the binaries, no need to recompile. So with this and cygwin I just use the method I had developed for the Unix servers.

- 1,490
- 13
- 22
Track instance numbers in a dynamodb table.
Querying and updating the table on scale-out is pretty straightforward using the user-data script. Updating the table on scale-in is more difficult and requires using autoscaling lifecycle hooks.

- 72
- 1
- 6