Best practice for creating multiple resources with Terraform
2 min readNov 7, 2021
Best Practice:
While using for_each, always keep index key name different than display name of the resource.
Problem statement:
While creating multiple resources through terraform, we need to ensure that any modification to the resource names later shouldn’t require resource to be destroyed and recreated. If a resource needs to be destroyed then it has larger implications as there could be various other resource dependencies on.
Solution:
How do you achieve this?
- Prefer for_each over count when creating number of resources.
- The index keys of the resources in the for_each map should not be same as the resource names.
Prefer for_each over count when creating number of resources.
- Count results into a list being created in the TF Statefile.
- This list has number indexes such as 0,1,2,..
- If you delete any intermediate element from this delete, then it results into manipulating all the other higher index resources.
- More specifically, if you are creating list of Instances, then it copies all the Instances one level up till the deleted Instance and then deletes the last one in the list.
Index key not same as resource names
Incorrect example -
# main.tf
resource "oci_core_instance" "test_instance" {
for_each = { for instance in var.instance_list: instance.name => instance }
# other parameters of instance creation
# ...}# variable.tf
variable "instances"{
type = list(object({
name = string # display name }))
}
- Converts list to map with the display name of instance as key of map created by for_each
- If later, anyone tries to modify the name of the instance, the respective key index is also modified.
- This results into recreating resource in the question.
Correct example -
# main.tf
resource "oci_core_instance" "test_instance" {
for_each = var.instances # other parameters of instance creation
# ...
}# variable.tf
variable "instances"{
type = map(object({
name = string # display name }))
}
- where instances is a map, having a different key to Instance object.
- Since key name is different than the display name, one can change the display name later without impacting the key of the element.