Back to Terraform

Count, For Each and Dynamic Blocks Without Address Surprises

November 5, 2026 Wasil Zafar 23 min read

Choose stable resource identities and distinguish resource repetition from value transformations

Table of Contents

  1. An Instance Key Becomes Part of the Address
  2. When Count Is the Simpler Honest Model
  3. Use For Each for Named Infrastructure Objects
  4. For Expressions Build Values, Not Resource Instances
  5. Dynamic Blocks Generate Nested Configuration
  6. Remove One Service Without Replacing Its Neighbors

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.

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.

An Instance Key Becomes Part of the Address
%%{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.

Position keys shift when a list changes; name keys do not A count model indexed 0 to 2 loses api from the middle. Batch moves from index 2 to index 1 and the old index 2 is destroyed, so three addresses are touched. A for_each model keyed by name loses only the api entry, while web and batch stay at their keys. Remove api: two keys, two outcomes count: the key is the position before after removing api [0] web [1] api [2] batch [0] web kept [1] batch replaced [2] destroyed one removal, three addresses touched batch is replaced even though it was not deleted for_each: the key is the name before after removing api ["web"] ["api"] ["batch"] ["web"] kept ["api"] destroyed ["batch"] kept one removal, one address touched web and batch keep their names and their objects A position describes where an object sits. A name describes which object it is.

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 : 0 disables the block cleanly; references must cope with absence, and one(terraform_data.service[*].id) returns the only id or null when 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.

When Count Is the Simpler Honest Model
%%{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.

# count-model/main.tf
terraform {
  required_version = "= 1.17.1"
}

locals {
  service_names = ["web", "api", "batch"]
  services = {
    web   = { port = 8080, replicas = 2 }
    api   = { port = 9090, replicas = 3 }
    batch = { port = 7070, replicas = 1 }
  }
}

resource "terraform_data" "service" {
  count = length(local.service_names)

  input = {
    name = local.service_names[count.index]
    port = local.services[local.service_names[count.index]].port
  }

  triggers_replace = local.service_names[count.index]
}

# foreach-model/main.tf
terraform {
  required_version = "= 1.17.1"
}

locals {
  services = {
    web   = { port = 8080, replicas = 2 }
    api   = { port = 9090, replicas = 3 }
    batch = { port = 7070, replicas = 1 }
  }
}

resource "terraform_data" "service" {
  for_each = local.services

  input = {
    name = each.key
    port = each.value.port
  }

  triggers_replace = each.key
}

output "service_ports" {
  value = { for name, service in local.services : name => service.port }
}
terraform init -input=false
terraform fmt -check
terraform plan
terraform apply -auto-approve
terraform state list

The restrictions are real and worth memorizing, because each produces a plan-time error rather than a surprise in production:

RestrictionWhy it fails at plan timeResponse
Keys must be known before applyA 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 -targetTreat that suggestion as a design warning, not a workflow
Sensitive values are refusedThe value identifies instances and always appears in plan and UI output, so sensitive variables, outputs and resource attributes are rejectedProject the keys: toset([for name, credential in local.credentials : name]). Names enter the address, credentials stay out
Impure functions are refuseduuid, bcrypt and timestamp are deferred during evaluation, so they cannot produce keysGenerate a name once, store it in configuration, and pass it in
There is no implicit list conversionA 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 coexistThe block accepts one repetition meta-argumentPick 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.

Lab

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.

  1. Create count-model/ and copy the count model from the code widget above into main.tf. Run terraform init -input=false, terraform fmt -check and terraform plan. Expect three objects to add, addressed terraform_data.service[0], [1] and [2].
  2. Apply with terraform apply -auto-approve, then run terraform state list. The three indexed addresses should appear, one per line.
  3. Create foreach-model/ and copy the for_each model from the widget into main.tf. Repeat init, plan and apply. Expect three objects again, now addressed with ["web"], ["api"] and ["batch"].
  4. Run terraform state list in foreach-model/ and compare it with the count model. Same count of objects, different identity scheme.
  5. In foreach-model/, add a fourth service to local.services and run terraform plan. Expect one add and no other address to change. Try the same edit in count-model/ by appending to the list and compare the summaries.
  6. Read terraform output service_ports. The for expression 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_each fails with an error that the value must be a map or a set of strings.
  • A variable feeding for_each and marked sensitive fails 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"]
    }
  }
}

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:

LimitRuleFailure you see
PlacementAllowed inside resource, data, provider and provisioner blocksNot a general repetition construct for arbitrary configuration
SchemaCan generate only nested block types the schema declaresA misspelled label is a validation error, not a new block type
Meta-argumentsCannot generate lifecycle or provisioner blocksThey must be written literally, because Terraform processes them before it is safe to evaluate expressions
ScopeGenerated blocks belong to the parent object; a dynamic block cannot create instances or fill argument positionsThe change appears on the parent resource
AddressesGenerated blocks have no address of their ownA 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.

A dynamic block expands one collection into nested blocks Three service entries in a local value are iterated by a dynamic ingress block with an iterator named rule. The result is three ingress blocks inside one security group. A dynamic lifecycle block is rejected because meta-arguments are processed before expressions are evaluated. One collection, three nested blocks local.services web / 8080 api / 9090 batch / 7070 three entries, one per service dynamic "ingress" for_each = local.services iterator = rule content { ... } generated inside one resource ingress { port 8080 } ingress { port 9090 } ingress { port 7070 } Rejected: dynamic "lifecycle" { ... } Meta-arguments are processed before expressions are evaluated, so a dynamic block cannot generate them. Only nested block types declared by the resource schema can be generated.

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.

ModelEditAddresses touchedPlan summary
countRemove api from the list[0] unchanged, [1] replaced, [2] destroyed1 to add, 2 to destroy
for_eachDelete the api entry["api"] destroyed0 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.

moved {
  from = terraform_data.service[0]
  to   = terraform_data.service["web"]
}

moved {
  from = terraform_data.service[1]
  to   = terraform_data.service["api"]
}

moved {
  from = terraform_data.service[2]
  to   = terraform_data.service["batch"]
}
terraform plan -out=tfplan
terraform show tfplan
terraform state list

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.

Lab

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.

  1. In count-model/, delete "api" from local.service_names and run terraform plan. Record every address in the output. Expect [0] unchanged, [1] replaced and [2] destroyed. Do not apply. Restore the list.
  2. In foreach-model/, delete the api entry from local.services and run terraform plan. Expect one destroy at terraform_data.service["api"] and no other address. Restore the entry.
  3. In count-model/, replace the count argument with the for_each form used in the other directory: for_each = local.services, name = each.key, port = each.value.port, triggers_replace = each.key. Add the moved blocks from the code widget above, one per old index, mapping [0] to ["web"], [1] to ["api"] and [2] to ["batch"].
  4. Run terraform fmt and terraform 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.
  5. Apply the move plan. Run terraform state list and confirm the addresses are now keyed by name.
  6. Now delete the api entry from local.services and plan again. Expect exactly one destroy, at terraform_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 moved blocks and the migration plan should propose three destroys and three creates.
  • Point two moved blocks 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.