Hi @venkatchkala88,
When you use count
Terraform understands that to mean that all of your resource instances are equivalent and so it shouldn’t matter which one gets destroyed when the count decreases.
For situations like yours where each database is unique and special, it’s more appropriate to use the for_each
argument and specify a meaningful name for each of the instances, which then means you can remove a particular key without affecting any others.
For example:
resource "example" "example" {
for_each = toset(["db1", "db2", "db3"])
# ...
}
If you had created the instances like above then you could remove db2
from the set of strings and Terraform will know exactly which instance you intend to remove, and will preserve the one you named “db3” because that name is still present in the set.
If you are using Terraform v1.1 or later then you can migrate to using for_each
at the same time as you remove “db2” by using the refactoring features:
# I'm using example.example here because you didn't
# mention exactly which resource type you are working
# with. You should replace this with the real resource type
# and resource name you are using, both here and in the
# "moved" blocks that follow.
resource "example" "example" {
for_each = toset(["db1", "db3"])
# ...
}
moved {
from = example.example[0]
to = example.example["db1"]
}
moved {
from = example.example[1]
to = example.example["db2"]
}
moved {
from = example.example[3]
to = example.example["db3"]
}
The configuration above will tell Terraform how to map your existing count-based indexes to the new instance keys chosen by for_each
, so Terraform will first translate your existing instances from numeric keys to string-based keys. After it’s done so, it will notice that example.example["db2"]
is no longer declared in the configuration and propose to destroy it. Therefore you should be able to apply the plan and have it keep both “db1” and “db3”, and only destroy “db2”.
If you try this, make sure to inspect the plan to make sure Terraform reports only that db1 and db3 have moved, without proposing to modify them in any way. The only real action you should see in the plan is the one proposing to delete example.example["db2"]
.
(You can choose whichever instance key strings you like when you do this, as long as you’re consistent. If there’s something more meaningful than just “db1” – for example, the name of the application or customer that the database belongs to – then I would suggest using that instead so that it’s easier for future maintainers to clearly see what is special about each of these instances.)