Auto increment EC2 instance Name

前端 未结 1 1800
南方客
南方客 2021-01-26 10:52

I have seen many questions on Stackoverflow asking if there is a way to auto-increment instance names. For example:

foo1
foo2
fooN

I am trying

1条回答
  •  被撕碎了的回忆
    2021-01-26 11:33

    The first thing is to decide what is meant by "auto-incrementing".

    For example, if these instances already exist:

    • foo1
    • foo2

    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:

    • foo1
    • foo3

    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

    0 讨论(0)
提交回复
热议问题