|
|
Terraform for_each and count
Author: Venkata Sudhakar
Terraform for_each lets you create multiple instances of a resource from a single resource block by iterating over a map or set. Instead of writing three nearly identical resource blocks for three GCS buckets, you write one block with for_each and let Terraform create all three. This keeps your configuration DRY (Do not Repeat Yourself) and makes it easy to add or remove resources by changing the input collection. count creates resources indexed by number (0, 1, 2...), while for_each creates them indexed by a meaningful key from your map or set. for_each is almost always preferred over count because removing an item from the middle of a count list causes Terraform to renumber and potentially destroy the wrong resources. for_each uses stable keys so removing one item only destroys that one resource. The below example shows creating three GCS buckets with for_each using a map, and referencing each instance using each.key and each.value.
It gives the following output,
terraform plan
+ google_storage_bucket.data["archive"]
name = "myproject-archive"
storage_class = "COLDLINE"
+ google_storage_bucket.data["processed"]
name = "myproject-processed"
storage_class = "NEARLINE"
+ google_storage_bucket.data["raw"]
name = "myproject-raw"
storage_class = "STANDARD"
Plan: 3 to add, 0 to change, 0 to destroy.
Outputs:
all_bucket_names = {
archive = "myproject-archive"
processed = "myproject-processed"
raw = "myproject-raw"
}
It gives the following output,
# for_each with set creates:
google_compute_network.vpc["dev"]
google_compute_network.vpc["prod"]
google_compute_network.vpc["staging"]
# Adding "qa" to the set only creates one new network:
+ google_compute_network.vpc["qa"]
# All existing networks are untouched - stable keys mean safe updates
Use for_each when each resource has a meaningful name (environments, regions, teams). Use count only for truly anonymous resources like N identical worker nodes. When in doubt, for_each is the safer choice because it uses stable string keys instead of numeric indexes.
|
|