In order to create multiple resources in terraform, we can use count
or for_each
. When we are using count on a list type variable to create multiple resources, terraform will create the state based on an index. If I delete a value in the list located at index somewhere in the middle of the list, all of the next resources will be deleted and recreated (due to the fact that all the next resources after that index are now changing their indexes number).
Since this is true, is there any reason why should I ever use count
instead of for_each
(which saves the state based on given key)?
If this is true, it means that I will need to create a key for every resource which I will ever create using a loop. Is this make sense?
It feels like I'm missing the point of count.
The Terraform count
meta-argument is not deprecated. It is true that it existed earlier than for_each
, and doesn't handle deletion of resources as elegantly as for_each
.
In your case you say you are using count
to create resources for each item in a list. In the instance where you have a list, set, or map variable representing resources to be created, then for_each
is definitely the correct thing to use.
However, if there are times you just need N
number of something, count
still works just fine. For example if you just had a numeric variable called number_of_servers
, or if you have a boolean variable called create_optional_server
, then in either of those cases count
makes perfect sense and you would have to jump through extra hoops to convert that into something you could pass to for_each
while not actually gaining any extra functionality from for_each
.