An Instance Key Becomes Part of the Address
Three services, one address each. The environment needs web on port 8080, api on 9090 and batch on 7070. Written as three resource blocks, each object has its own address and nothing can blur them. Written as one block that repeats, Terraform needs a way to tell the copies apart, and the mechanism it chooses becomes part of your interface to the infrastructure.
The key is the address, not a label
The block address terraform_data.service names the block. With repetition enabled, each real object is recorded at a longer address, and plans, state and references all use the long form. The key is not metadata attached to the object: it is the part of the address that identifies which object Terraform believes it is managing. Change the key and you have told Terraform that a different object should occupy that slot.
Think lockers and pigeonholes. Numbered lockers identify a space: take locker 2 out of service and every later locker is renumbered. Named pigeonholes identify a recipient: taking out the slot labelled api leaves web and batch exactly where they were. Both store the same number of items; only one survives a deletion without disturbing its neighbours.
Figure 1 follows the address from the block to the plan decision. A repeated block appends a key, and the plan matches that full address against the state: a match updates the object, a desired address with no recorded object is a create, and a recorded address with no desired object is a destroy.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["One block: terraform_data.service"] --> B{"Does the block repeat?"}
B -->|"no"| C["Address: terraform_data.service"]
B -->|"count"| D["Address: terraform_data.service[0]"]
B -->|"for_each"| E["Address: terraform_data.service[#quot;api#quot;]"]
C --> F["Plan matches address against state"]
D --> F
E --> F
F --> G{"Same address recorded?"}
G -->|"yes"| H["Update that one object"]
G -->|"no"| I["Create a new object"]
I --> J["The unmatched old address is destroyed"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,B,F primary;
class C,D,E secondary;
class H ok;
class I,J danger;
Terraform compares addresses, not the name argument. If index 1 held api yesterday and the configuration now says index 1 is batch, the plan says index 1 changes. Whether that is an in-place update or a replacement depends on the provider schema; the identity decision was made by the key.
Figure 2 shows the same deletion under both key styles: positions shift, names do not.
One reference set throughout. The rest of the article uses this three-service set, held in a local map so every section refers to the same objects. Examples use Terraform CLI 1.17.1 and the built-in terraform_data resource; the dynamic-block illustration follows the hashicorp/aws 6.72.0 schema. Both versions were current on 5 November 2026.
When Count Is the Simpler Honest Model
Count is arithmetic. It takes a whole number and creates that many instances, numbered from zero, and count.index inside the block supplies the current number.
Count is honest in three narrow cases:
- Fixed-size pool. Identical workers where ordinal identity is meaningless, such as three cache nodes addressed collectively.
- Optional resource.
count = var.create_service ? 1 : 0disables the block cleanly; references must cope with absence, andone(terraform_data.service[*].id)returns the only id ornullwhen the collection is empty. - Short-lived experiment. Destroyed before names matter.
One deletion can touch three addresses. With state holding three services at indexes 0 to 2, remove the middle one and the configuration asks for two. Index 0 is unchanged. Index 1 was api and must become batch, so that object is updated or replaced. Index 2 has no desired counterpart, so it is destroyed.
The summary hides the damage. The plan may read 1 to add, 2 to destroy, which sounds modest until you notice that batch โ an object nobody asked to change โ is the one being replaced. If the list is a set of database names, the replacement can mean a new database with an empty disk.
This is not a Terraform bug
Count has no way to know that batch is the same batch as before, because the key it was given was a position. The configuration said the object at index 1 is now batch, and Terraform compares addresses and agrees. Reaching for -target does not fix the design, it postpones it.
Two planning restrictions follow. The count value must be known before Terraform performs any remote operation, so it cannot depend on an attribute that the provider only returns after creation. A count that reaches zero also removes the block's objects entirely, which is why references need a null-safe read rather than a bare index.
One exception helps. Adding count to a resource that had no meta-argument makes Terraform propose moving the existing object to index 0. That keeps the first instance but does nothing for a list that is later reordered, so write the moved block explicitly when reviewers need to see the intent.
Count stops being the right answer the moment a human would refer to one instance by name. Services, buckets, DNS records and IAM users are named objects, and a position is a poor proxy for a name.
Figure 3 draws the decision and its failure branches. An unknown count stops at plan time. A middle deletion passes the plan check and silently renumbers every object after it.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["count = length(local.service_names)"] --> B{"Value known at plan time?"}
B -->|"no"| B1["Error: count depends on an apply-time value"]
B -->|"yes"| C["Instances numbered 0 to n-1"]
C --> D{"What changed in the list?"}
D -->|"appended"| D1["New highest index created"]
D -->|"removed last"| D2["Last index destroyed"]
D -->|"removed middle"| D3["Every later item shifts down one index"]
D3 --> D4["Neighbouring objects are updated or replaced"]
D4 -.-> E["for_each keeps each object at its name key"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,B,C primary;
class D secondary;
class D1,D2 ok;
class B1,D3,D4 danger;
class E warn;
Use For Each for Named Infrastructure Objects
Repetition by key. for_each takes a map or a set of strings and creates one instance per element; the map key, or the set member, becomes the instance key in the address. Inside the block, the each object exposes a key and a value, and for a set the two are the same string โ which is why a set is appropriate when the name is the whole configuration.
A map key is chosen by you and stays with the object. Removing api from the service map removes one address and nothing else. It does not renumber batch, because batch never had a number.
A map usually carries configuration better. Each entry holds a port and a replicas count: the key names the instance and the value configures it, so the object's identity is the same string a reader would use in conversation. Terraform's for_each reference calls this the right tool when instance arguments must differ in ways an integer cannot express.
The restrictions are real and worth memorizing, because each produces a plan-time error rather than a surprise in production:
| Restriction | Why it fails at plan time | Response |
|---|---|---|
| Keys must be known before apply | A key derived from an id the provider assigns during creation cannot identify an instance during planning; Terraform reports a value that cannot be determined until apply and suggests -target | Treat that suggestion as a design warning, not a workflow |
| Sensitive values are refused | The value identifies instances and always appears in plan and UI output, so sensitive variables, outputs and resource attributes are rejected | Project the keys: toset([for name, credential in local.credentials : name]). Names enter the address, credentials stay out |
| Impure functions are refused | uuid, bcrypt and timestamp are deferred during evaluation, so they cannot produce keys | Generate a name once, store it in configuration, and pass it in |
| There is no implicit list conversion | A list or tuple must go through toset() | Duplicates collapse and order stops mattering, which is exactly the point of a set |
count and for_each cannot coexist | The block accepts one repetition meta-argument | Pick one for the block; a mixed shape needs two resources |
Name the object, not its position
A set is the right model when the only fact about an instance is its name. A map is the right model when the name carries settings, because each.value then saves you from indexing a separate lookup table by hand. Count remains the right answer only while the instances are homogeneous and their number is the only thing that varies.
Run both models side by side
Execution status: design-only. This is a procedure for you to run. No plan output below is quoted as a measurement.
Prerequisites. Terraform CLI 1.17.1 on your PATH (terraform version must report it), a scratch directory and a shell. Both models use the built-in terraform_data resource, available since Terraform 1.4, so init needs no provider download, cloud account or credential.
- Create
count-model/and copy the count model from the code widget above intomain.tf. Runterraform init -input=false,terraform fmt -checkandterraform plan. Expect three objects to add, addressedterraform_data.service[0],[1]and[2]. - Apply with
terraform apply -auto-approve, then runterraform state list. The three indexed addresses should appear, one per line. - Create
foreach-model/and copy thefor_eachmodel from the widget intomain.tf. Repeat init, plan and apply. Expect three objects again, now addressed with["web"],["api"]and["batch"]. - Run
terraform state listinforeach-model/and compare it with the count model. Same count of objects, different identity scheme. - In
foreach-model/, add a fourth service tolocal.servicesand runterraform plan. Expect one add and no other address to change. Try the same edit incount-model/by appending to the list and compare the summaries. - Read
terraform output service_ports. Theforexpression produces a map from name to port; it creates no resources and changes no address.
Expected observation. The count model stores positions and the for_each model stores names. Appending is safe in both. Removing from the middle is only safe in the keyed model, which the next card tests.
Failure check. Each mistake should stop at plan time rather than reach an apply:
- A list assigned directly to
for_eachfails with an error that the value must be a map or a set of strings. - A variable feeding
for_eachand markedsensitivefails with an error about sensitive values in instance keys. - A key taken from an id known only after apply fails with an error about a value that cannot be determined until apply.
Cost and cleanup. Zero. The built-in terraform_data resource keeps state local, and no secrets are involved. Run terraform destroy -auto-approve in both directories, then delete them.
For Expressions Build Values, Not Resource Instances
A for expression transforms one collection into a value. It does not create a resource, change an address or appear in state. Mapping a name list through a function produces a tuple of strings; a braced form produces an object from name to port, and the service_ports output in the previous card is exactly that.
Three parts: an input, an optional pair of symbols, a result. The first symbol is the key over a map and the index over a list, so a two-symbol form over a list numbers the entries; with one symbol it always means the value.
An if clause filters per element. Filtering the service map on replicas > 1 returns only web and api. That is the clean way to split one source of truth into two views, such as enabled and disabled services.
The brackets decide the result type, not the input. Square brackets always produce a tuple; braces always produce an object and require a key-value pair. Automatic conversion usually bridges the difference, but a variable declared with a concrete collection type is a contract, so wrap the result at that boundary with tolist, tomap or toset rather than trusting the conversion.
Objects require unique keys by default. A duplicate key is an error, and grouping mode changes that: adding ... after the value expression collects every match into a list, turning a name-to-count map into a count-to-names map. It is a small feature with a large payoff when you need to invert a lookup.
Ordering is not preserved the way you expect. A map or object is sorted by key lexically; a set of strings is sorted by value; a set of other types has an arbitrary order that may change between versions. Convert with toset() when the consumer should treat the result as unordered.
A for expression cannot produce nested blocks inside a resource. The configuration language evaluates expressions in argument positions, and a block position is not an argument position. That gap is exactly what the next section fills.
Three mechanisms, three jobs. A for expression builds a value, count and for_each build resource instances, and dynamic builds nested blocks inside one resource. Most "why did my plan change" incidents come from treating one of these as another.
Dynamic Blocks Generate Nested Configuration
Some parts of a resource are blocks, not arguments. They are repeatable nested blocks: ingress rules in a security group, settings in an environment, rules in a ruleset. You cannot place a for expression where a block is expected, and you cannot write a variable number of literal blocks. A dynamic block exists for that case.
The label must name a nested block type the provider schema defines. The block's for_each accepts any collection or structural value, not only a map or set.
The body and the symbol are configurable. An optional iterator defaults to the label, content holds the generated body, and a labels argument supplies labels for block types that take them.
Keep the illustration out of the lab. It is written against hashicorp/aws 6.72.0 and would make Terraform install the AWS provider if it were saved as a .tf file beside the others.
# illustration only: hashicorp/aws 6.72.0, not applied in this lab
resource "aws_security_group" "services" {
name = "services"
dynamic "ingress" {
for_each = local.services
iterator = rule
content {
description = "${rule.key} service"
from_port = rule.value.port
to_port = rule.value.port
protocol = "tcp"
cidr_blocks = ["10.0.0.0/8"]
}
}
}
Name the iterator when blocks nest
Iterator naming is cosmetic in a single-level block and essential in a nested one. Without an explicit iterator, the symbol takes the block label, so two nested blocks with the same label shadow each other and the inner body cannot reach the outer value. Give the outer and inner iterators different names, as the reference's origin_group and origin example does, and both stay visible.
The dynamic blocks reference puts it plainly: a dynamic block is a for expression that produces blocks instead of a value. Its iterator exposes the same key and value pair, and for a set the two are equal.
The limits are more important than the syntax:
| Limit | Rule | Failure you see |
|---|---|---|
| Placement | Allowed inside resource, data, provider and provisioner blocks | Not a general repetition construct for arbitrary configuration |
| Schema | Can generate only nested block types the schema declares | A misspelled label is a validation error, not a new block type |
| Meta-arguments | Cannot generate lifecycle or provisioner blocks | They must be written literally, because Terraform processes them before it is safe to evaluate expressions |
| Scope | Generated blocks belong to the parent object; a dynamic block cannot create instances or fill argument positions | The change appears on the parent resource |
| Addresses | Generated blocks have no address of their own | A plan can look quiet while a security group's rules changed |
Figure 4 shows the expansion and the rejected branch: three service definitions become three ingress blocks inside one resource, while a lifecycle attempt stops at validation because there is nothing for it to generate.
Dynamic is the exception, not the default
The best-practice guidance is blunt: write nested blocks literally wherever possible, and reserve dynamic for a reusable module that must accept a variable-length structure. If most of a resource's arguments map one-to-one from an input variable, the module may not be providing an abstraction at all. A dynamic block also hides structure, because the rendered resource depends on values that live elsewhere.
Remove One Service Without Replacing Its Neighbors
The api service is being retired. The operation should remove one object; under count it also rewrites two neighbours. The addresses, not the object count, tell you which model you are running.
| Model | Edit | Addresses touched | Plan summary |
|---|---|---|---|
count | Remove api from the list | [0] unchanged, [1] replaced, [2] destroyed | 1 to add, 2 to destroy |
for_each | Delete the api entry | ["api"] destroyed | 0 to add, 1 to destroy |
The replacement is not an in-place update. The count model sets triggers_replace, so the object at index 1 is recreated. The difference between the two plans is not the number of objects you meant to remove; it is the number of objects the plan touches.
A plan summary is a poor review signal on its own. Read the addresses, and save the plan when the run matters: the number of destroyed addresses should equal the number you intended to remove, and a larger number means an index moved.
Migrating a positional model to names need not replace anything. Terraform 1.1 and later support moved blocks with explicit instance keys, and the refactoring documentation shows the index-to-name mapping. Write one block per old index, apply the moves against the unchanged map, then delete api. In that order the move plan has no adds or destroys, and the deletion touches one address.
Move first, verify, then remove. If you delete api from the map and add the moved blocks in the same change, a move can target a key the new configuration no longer declares, so the plan mixes a move with a destroy.
Keep the moved blocks after the apply. They are the upgrade path for state files that still contain the old addresses, and removing them later is a breaking change. The refactoring article covers removed blocks and state commands; for now, the rule is that moves are cheap, previewed in the plan and safe to leave in place.
Stabilize instance identities
Execution status: design-only. This lab is a procedure, not a claim about results. Run it in the two scratch directories from the previous card.
Prerequisites. Both directories applied with Terraform CLI 1.17.1, no cloud account, and a plan you are willing to discard. Keep a copy of each main.tf before editing.
- In
count-model/, delete"api"fromlocal.service_namesand runterraform plan. Record every address in the output. Expect[0]unchanged,[1]replaced and[2]destroyed. Do not apply. Restore the list. - In
foreach-model/, delete theapientry fromlocal.servicesand runterraform plan. Expect one destroy atterraform_data.service["api"]and no other address. Restore the entry. - In
count-model/, replace thecountargument with thefor_eachform used in the other directory:for_each = local.services,name = each.key,port = each.value.port,triggers_replace = each.key. Add themovedblocks from the code widget above, one per old index, mapping[0]to["web"],[1]to["api"]and[2]to["batch"]. - Run
terraform fmtandterraform plan. Expect three moves and no additions or destructions. The plan should show each old address as moved to its new key rather than as a destroy/create pair. - Apply the move plan. Run
terraform state listand confirm the addresses are now keyed by name. - Now delete the
apientry fromlocal.servicesand plan again. Expect exactly one destroy, atterraform_data.service["api"]. Apply it if you want the final state.
Expected observation. The count plan touches three addresses for a one-object deletion. The keyed plan touches one. The mapped migration produces moves instead of replacements, and only the final deletion changes the object count.
Failure check. Three mistakes are worth naming, because each has a distinct symptom:
- Skip the
movedblocks and the migration plan should propose three destroys and three creates. - Point two
movedblocks at the same new address and Terraform should reject the configuration as ambiguous. - Apply the count edit without reading the plan and batch is replaced, which is the outcome this lab exists to prevent.
Cost and cleanup. Zero. Both directories use the built-in terraform_data resource and local state, and no sensitive values are stored. Run terraform destroy -auto-approve in each directory, then delete them. If you applied the moved version, destroy from the migrated directory so the keyed addresses are the ones removed.
Next in the Series
In Providers, Resources and Data Sources: Who Owns the Object?, we'll explore Select provider schemas and distinguish managed ownership from reading existing infrastructure.