Infrastructure as code · Intermediate · 22 min
Repeat resources in Terraform with count, for_each and dynamic blocks
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Terraform 1.17.2 · hashicorp/local 2.9 · hashicorp/random 3.9 · hashicorp/archive 2.8
You will build a small Terraform 1.17 project that makes one file per page with count, watch count recreate the wrong things when a list shrinks, rebuild it with for_each and stable keys, shape the outputs with for expressions and splat, generate nested blocks with dynamic, and leave with a rule for when to use each.
On this page
Sooner or later a Terraform configuration needs several of the same thing: one bucket per environment, one DNS record per service, one firewall rule per port. Terraform gives you three tools for that. count makes a numbered list of copies of a resource. for_each makes a named set of copies, one per key. dynamic repeats a nested block inside a single resource. They look interchangeable in small examples and behave very differently the day someone removes an item.
In this tutorial you make one text file per page of a tiny website, first with count, then with for_each, and you see the difference in the plan when a page is removed from the middle of the list. Then you shape the outputs, bundle the pages into a zip with a dynamic block, and use count for the one job it is best at: switching a resource on or off.
Everything runs on your machine with three small HashiCorp providers: local writes files, random makes IDs, and archive builds zip files. Nothing talks to a cloud account, so nothing bills, and the provider downloads are a fraction of the size of a cloud provider, which helps if you pay for data by the gigabyte. The language features are the same in OpenTofu 1.13, so the files should work unchanged with tofu in place of terraform.
Step 1 · Create the project and pin the providers
Make a throwaway folder for this tutorial and check your Terraform version:
mkdir -p ~/repeat-demo
cd ~/repeat-demo
terraform versionWrite versions.tf. Each ~> constraint sets the current minor version as a floor and blocks the next major version: ~> 2.9 allows 2.9, 2.10 and any later 2.x but not 3.0, and ~> 1.17 does the same for Terraform 1.x. A later major release therefore cannot change behaviour under you:
cat > versions.tf <<'HCL'
terraform {
required_version = "~> 1.17"
required_providers {
local = {
source = "hashicorp/local"
version = "~> 2.9"
}
random = {
source = "hashicorp/random"
version = "~> 3.9"
}
archive = {
source = "hashicorp/archive"
version = "~> 2.8"
}
}
}
HCLDeclare one input, the list of pages, and give it a value in terraform.tfvars, which Terraform reads on every run without being told:
cat > variables.tf <<'HCL'
variable "pages" {
type = list(string)
description = "Page names for the site. Each one becomes a file."
}
HCL
cat > terraform.tfvars <<'HCL'
pages = ["home", "about", "contact"]
HCL
terraform initCheck it worked
terraform version prints Terraform v1.17.2 or a later 1.17 release. terraform init lists hashicorp/local, hashicorp/random and hashicorp/archive being installed and ends with Terraform has been successfully initialized!. A .terraform.lock.hcl file now sits in the folder.
Step 2 · Make one file per page with count
count takes a whole number and makes that many copies of a resource. Inside the block, count.index is the copy's position, starting at 0, and you use it to pick the matching item from the list. Write main.tf:
cat > main.tf <<'HCL'
resource "random_id" "page" {
count = length(var.pages)
byte_length = 4
keepers = {
name = var.pages[count.index]
}
}
resource "local_file" "page" {
count = length(var.pages)
filename = "${path.module}/site-v1/${var.pages[count.index]}.txt"
content = "page=${var.pages[count.index]} id=${random_id.page[count.index].hex}\n"
}
HCLEach page gets a random ID, standing in for something you would hate to lose in real life: a database password, a generated bucket suffix, an API key. keepers ties the ID to the page name, so the ID changes only if the name it belongs to changes.
Add an output that lists the file names. local_file.page is a list here, and [*] (the splat operator) takes one attribute from every element:
cat > outputs.tf <<'HCL'
output "files" {
value = local_file.page[*].filename
}
HCL
terraform plan -out=count.tfplan
terraform apply count.tfplanLook at what Terraform recorded and at one of the files:
terraform state list
cat site-v1/contact.txtCheck it worked
The plan ended with Plan: 6 to add, 0 to change, 0 to destroy. and the apply with Apply complete! Resources: 6 added, 0 changed, 0 destroyed. The output files lists ./site-v1/home.txt, ./site-v1/about.txt and ./site-v1/contact.txt. terraform state list shows six addresses with numbers in brackets: local_file.page[0] to local_file.page[2] and random_id.page[0] to random_id.page[2]. contact.txt holds a line like page=contact id=3f9a01c2. Note your ID, because the next step threatens it.
Step 3 · Remove a page from the middle and read the plan
The site no longer needs an about page. Remove it from the list:
cat > terraform.tfvars <<'HCL'
pages = ["home", "contact"]
HCL
terraform planDo not apply this plan. Read it instead. You removed one page, but the plan ends with Plan: 2 to add, 0 to change, 4 to destroy. Here is why. Terraform tracks count copies by position. Before, position 1 was about and position 2 was contact. Now the list has two items, so:
- Position 0 is still
home. Nothing changes. - Position 1 is now
contact. Its keeper changed fromabouttocontact, sorandom_id.page[1]must be replaced, andlocal_file.page[1]must be replaced because its file name changed. - Position 2 no longer exists, so
random_id.page[2]andlocal_file.page[2]will be destroyed, along with the ID thatcontacthad.
The contact page itself did not change, yet it would lose its ID and get a new one. With a password or a disk instead of a random ID, that is an outage. There is a second problem hiding here: the new local_file.page[1] writes contact.txt while the old local_file.page[2] deletes contact.txt, and nothing fixes the order of those two, so the file could end up gone.
Put the list back the way it was:
cat > terraform.tfvars <<'HCL'
pages = ["home", "about", "contact"]
HCL
terraform planCheck it worked
The first plan shows random_id.page[1] must be replaced, random_id.page[2] will be destroyed and the 2 to add, 0 to change, 4 to destroy summary. After you restore the list, the plan says No changes. Your infrastructure matches the configuration.
Step 4 · Switch to for_each so each page has a stable key
for_each takes a map or a set of strings and makes one copy per key. Terraform tracks each copy by its key, not by its position, so removing one key touches only that copy. Inside the block, each.key is the key and each.value is the value (for a set, both are the same string).
Rewrite main.tf. toset() turns the list into a set of page names. The second resource uses for_each = random_id.page, which hands it the first resource's map of copies: each.key is the page name and each.value is that page's random_id, so the two stay paired by name. The files go into a new folder, site, so the old and new files never share a path:
cat > main.tf <<'HCL'
resource "random_id" "page" {
for_each = toset(var.pages)
byte_length = 4
keepers = {
name = each.key
}
}
resource "local_file" "page" {
for_each = random_id.page
filename = "${path.module}/site/${each.key}.txt"
content = "page=${each.key} id=${each.value.hex}\n"
}
HCLThe output needs a change too. With for_each, local_file.page is a map keyed by page name, and the splat operator only works on lists. values() turns the map into a list, sorted by key:
cat > outputs.tf <<'HCL'
output "files" {
value = values(local_file.page)[*].filename
}
HCL
terraform plan -out=foreach.tfplanThe plan ends with Plan: 6 to add, 0 to change, 6 to destroy. The resources are the same kind with the same names, but their addresses changed from local_file.page[0] to local_file.page["home"], and Terraform treats a new address as a new resource. On a real project you would add moved blocks so the plan shows moves instead of replacements; the tutorial on moved blocks does exactly that conversion. Here the files are disposable, so apply the plan:
terraform apply foreach.tfplan
terraform state listCheck it worked
terraform state list now shows keys in quotes: local_file.page["about"], local_file.page["contact"], local_file.page["home"] and the same three for random_id.page. ls site shows about.txt, contact.txt and home.txt, and site-v1 holds no files. The files output lists the paths in key order: about, contact, home.
Step 5 · Remove the middle page again
Save a copy of the contact page so you can compare it afterwards, then remove about from the list:
cp site/contact.txt /tmp/contact-before.txt
cat > terraform.tfvars <<'HCL'
pages = ["home", "contact"]
HCL
terraform plan -out=remove.tfplanThis time the plan ends with Plan: 0 to add, 0 to change, 2 to destroy., and the two resources it names are random_id.page["about"] and local_file.page["about"]. Nothing else moves, because contact is still contact. Apply it and compare:
terraform apply remove.tfplan
diff /tmp/contact-before.txt site/contact.txt && echo "contact page unchanged"Check it worked
The apply reports Resources: 0 added, 0 changed, 2 destroyed. diff prints nothing and the shell prints contact page unchanged: the contact page kept its ID. site/about.txt is gone.
Step 6 · Shape outputs with for expressions and splat
Outputs are how other modules, scripts and people read values from a configuration, and they rarely want a resource exactly as Terraform stores it. Two tools do most of the shaping. A splat ([*]) pulls one attribute from every element of a list. A for expression builds a new list or map from any collection, and can filter with if.
Try a few in terraform console before you commit to them. It reads expressions from standard input and prints each result:
printf '%s\n' \
'values(local_file.page)[*].filename' \
'{ for name, r in random_id.page : name => r.hex }' \
'[for name, f in local_file.page : f.filename if name != "home"]' \
'keys(local_file.page)' \
| terraform consoleRead the four results in order:
values(local_file.page)[*].filenamegives a list of the two file paths.{ for name, r in random_id.page : name => r.hex }uses curly braces, so it builds a map from page name to ID. With a map, theforgives you the key first and the value second.[for ... if name != "home"]uses square brackets, so it builds a list, and theifkeeps only the pages that are nothome.keys()lists the keys, always in sorted order.
Keep the two that are useful as outputs. Append them to outputs.tf:
cat >> outputs.tf <<'HCL'
output "ids_by_page" {
value = { for name, r in random_id.page : name => r.hex }
}
output "secondary_pages" {
value = [for name, f in local_file.page : f.filename if name != "home"]
}
HCL
terraform plan -out=outputs.tfplan
terraform apply outputs.tfplan
terraform output -json ids_by_pageCheck it worked
The plan only lists Changes to Outputs, because no resource changes; applying it stores the new outputs. terraform output -json ids_by_page prints a JSON object with two keys, contact and home, each with an eight-character hex ID, and the contact ID matches the one in site/contact.txt. terraform output secondary_pages lists only ./site/contact.txt.
Step 7 · Generate nested blocks with dynamic
count and for_each repeat whole resources. Sometimes you need one resource with a repeated block inside it, such as one ingress rule per port in a cloud firewall. Writing those blocks by hand means editing the resource every time the list changes. A dynamic block generates them from a collection.
The archive_file data source builds a zip and takes one source block per file in it, which makes it a good place to practise. You will use unzip to look inside the result:
sudo apt update
sudo apt install -y unzipWrite bundle.tf. The dynamic "source" block makes one source block for every entry in local_file.page. Inside content, the name of the block (source) becomes the iterator, so source.key is the page name and source.value is that page's local_file:
cat > bundle.tf <<'HCL'
data "archive_file" "site" {
type = "zip"
output_path = "${path.module}/dist/site.zip"
dynamic "source" {
for_each = local_file.page
content {
filename = "${source.key}.txt"
content = source.value.content
}
}
}
output "bundle_bytes" {
value = data.archive_file.site.output_size
}
HCL
terraform plan -out=bundle.tfplan
terraform apply bundle.tfplan
unzip -l dist/site.zipThe data source builds the zip while Terraform plans, so dist/site.zip exists before the apply; the apply stores the bundle_bytes output. Add a page to terraform.tfvars later and the zip gains a file with no change to bundle.tf.
The same trick switches a single optional block on or off: for_each = var.enable_logging ? [1] : [] makes one block or none. Use dynamic sparingly. A resource whose every block is generated is hard to read in review, so write blocks out by hand when there are only one or two and they rarely change.
Check it worked
unzip -l lists contact.txt and home.txt, with no about.txt, and a total of 2 files. terraform output bundle_bytes prints the size of the zip in bytes, a number of a few hundred.
Step 8 · Use count as an on/off switch
count is still the right tool when the question is "do I want this at all?" rather than "how many of these?". A count of 1 or 0 turns a resource on or off. Add a robots.txt file that you can disable per environment:
cat > robots.tf <<'HCL'
variable "publish_robots" {
type = bool
description = "Write a robots.txt file for the site."
default = true
}
resource "local_file" "robots" {
count = var.publish_robots ? 1 : 0
filename = "${path.module}/site/robots.txt"
content = "User-agent: *\nAllow: /\n"
}
output "robots_file" {
value = one(local_file.robots[*].filename)
}
HCL
terraform plan -out=robots.tfplan
terraform apply robots.tfplanone() turns a list of zero or one items into the item itself, or null when the list is empty, so the output reads cleanly in both cases. Now ask what turning it off would do, without applying:
terraform plan -var publish_robots=falseThat leaves a simple rule of thumb:
- Use
countfor a yes or no: one copy or none, set by a boolean. - Use
for_eachfor a collection of things that have names, even if today the names are only a list of strings. A stable key is what lets you remove one item without touching the others. Think of a site translated into English, French, Swahili and Hausa: key the pages by language code and dropping French later destroys only the French pages. - Use
countwith a number only when the copies are truly identical and interchangeable, such as a pool of workers where losing the last one is the same as losing any other. - Use
dynamicfor nested blocks driven by data, and write them out by hand when there are only a few.
Check it worked
The apply reports 1 added, site/robots.txt exists and terraform output robots_file prints "./site/robots.txt". The plan with publish_robots=false shows local_file.robots[0] will be destroyed and Plan: 0 to add, 0 to change, 1 to destroy., and changes the robots_file output to null.
Step 9 · Clean up
Destroy everything the project created, using a saved destroy plan so you see the list before it runs:
terraform plan -destroy -out=destroy.tfplan
terraform apply destroy.tfplan
terraform state listThe zip in dist came from a data source, which Terraform reads but does not destroy, and the empty folders stay behind. Remove the whole project folder and the saved copy:
cd ~
rm -rf ~/repeat-demo /tmp/contact-before.txtCheck it worked
The destroy plan lists five resources, two random_id, two page files and robots.txt, and the apply ends with Apply complete! Resources: 0 added, 0 changed, 5 destroyed. terraform state list prints nothing. ls ~/repeat-demo reports that the folder does not exist.
Next steps
- Convert an existing
countresource tofor_eachwithout recreating anything in rename and move Terraform resources with moved blocks. - Stop an accidental removal from destroying something important with lifecycle rules in Terraform.
- Use these patterns in a real project layout in lay out the Relay OpenTofu project.
- Go back over plan, apply and state in manage infrastructure with OpenTofu.
Related tutorials
- Turn the Relay network into a reusable OpenTofu moduleYou will move Relay's VPC, subnets, routes and web security group into a local modules/network module with its own inputs, outputs and README, and adopt the 18 running objects with moved blocks so the plan destroys nothing.
- Test the Relay network module with tofu test and mock providersYou will have a tofu test suite for Relay's network module that checks subnet ranges, input validation and outputs against a mocked AWS provider, and passes in seconds with no credentials.
- Store the Relay state in S3 with locking and OpenTofu state encryptionYou will create a state bucket from a separate bootstrap configuration, move the Relay state into it with S3 locking, and encrypt that state and every saved plan with OpenTofu's own encryption, ready to switch to AWS KMS.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials