The first thing is to decide what is meant by "auto-incrementing".
For example, if these instances already exist:
then obviously the next instance would be foo3
.
But let's say that an instance has previously been terminated because load reduced, and the currently-running instances are:
Then the question is whether the next instance should be foo2
or foo4
.
If the answer is foo4
, then think of the situation where foo4
is later terminated and another instance is launched. Should it be foo4
or foo5
(since there was previously a foo4
).
It really boils down to determining why you want an auto-incremented name.
The reasons are typically:
- The need for a unique name
- The need for a human-friendly name
- The need for a hint as to the order in which instances where launched
If the need is for a unique name, then the Instance ID can fulfil this need perfectly, without needing an additional name.
Let's assume you want to go with a human-friendly name and you are okay to re-use names that were previously used (eg if foo1
and foo3
exists, then use foo2
next). In such a case, you would need something that logically inspects the existing instances and finds the first unused number.
If, on the other hand, you never wanted to re-use names, then you would need some place to store the 'current' number so that it can be incremented for the next instance.
Then, finally, comes the question of how to assign the auto-incremented name (which is your original question, but the above is also very important to understand first). My recommendation would be:
- Add some code to each instance that is triggered through the User Data so that it will run when the instance is launched (eg PowerShell)
- The code will inspect the existing instances with
describe-instances
or the place where the count is kept, then assign itself the next number
- The code can then call
create-tags
on itself, adding a Name
tag with the appropriate name