count, for_each, and Dynamic Blocks

Create many resources from one block with count and for_each, avoid the index-shift trap, make resources conditional, and generate nested blocks with dynamic.

By The Dark DebuggerUpdated 23 min read

This tutorial is about multiplying resources: creating several from one block with count and for_each, switching a resource on or off with a variable, and generating repeated nested blocks with dynamic. It builds on Variables, Locals, Outputs, and Expressions (you'll use for expressions constantly) and Providers and Resources (resource addresses and reading plans). The examples run locally with the local, random and archive providers, and the AWS security group examples are validated and planned.

Why this matters

A platform team runs three internal services: checkout, cart and search. Each needs a config file, a database password and a secrets file. Written out by hand that's nine resource blocks that differ only in a name and a port, and the fourth service means copying three more blocks and hoping nobody misses one.

Terraform's answer is to describe the collection once: a variable holding the services, and one block per kind of resource that says "one of these for each service". Adding a service becomes a one-line change. There are two meta-arguments that do this, count and for_each, and choosing the wrong one is behind one of the most destructive surprises in Terraform. We'll trigger that surprise on purpose.

count: a number of copies

count takes a whole number and creates that many instances of the resource. Inside the block, count.index is the instance's position, starting at 0:

terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.5"
    }
  }
}
 
variable "workers" {
  type    = list(string)
  default = ["web-a", "web-b", "web-c"]
}
 
resource "local_file" "worker" {
  count = length(var.workers)
 
  filename        = "${path.module}/out/${var.workers[count.index]}.conf"
  content         = "name=${var.workers[count.index]}\nslot=${count.index}\n"
  file_permission = "0644"
}
 
output "worker_files" {
  value = local_file.worker[*].filename
}
terraform apply -auto-approve
[…]
local_file.worker[1]: Creating...
local_file.worker[0]: Creating...
local_file.worker[1]: Creation complete after 0s [id=6c88bbdc7672b1da9348b3311b35b782928de0f9]
local_file.worker[2]: Creating...
local_file.worker[0]: Creation complete after 0s [id=346706bba73b15e4f5cb6656296368a013784829]
local_file.worker[2]: Creation complete after 0s [id=6aa5d25f5256894687d5f8d56588fb90b851d707]
 
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
 
Outputs:
 
worker_files = [
  "./out/web-a.conf",
  "./out/web-b.conf",
  "./out/web-c.conf",
]

The instances are addressed by position: local_file.worker[0], [1], [2]. The resource as a whole, local_file.worker, is now a list, so you index it or splat it:

> local_file.worker[0].filename
"./out/web-a.conf"
> local_file.worker[*].filename
[
  "./out/web-a.conf",
  "./out/web-b.conf",
  "./out/web-c.conf",
]
> length(local_file.worker)
3

(That's terraform console, introduced in the variables tutorial.)

The index-shift problem

Now decommission web-b, the middle worker. Remove it from the list and plan:

terraform plan -var 'workers=["web-a","web-c"]'
[…]
  # local_file.worker[1] must be replaced
-/+ resource "local_file" "worker" {
      ~ content              = <<-EOT # forces replacement
          - name=web-b
          + name=web-c
            slot=1
        EOT
[…]
      ~ filename             = "./out/web-b.conf" -> "./out/web-c.conf" # forces replacement
[…]
    }
 
  # local_file.worker[2] will be destroyed
  # (because index [2] is out of range for count)
  - resource "local_file" "worker" {
      - content              = <<-EOT
            name=web-c
            slot=2
        EOT -> null
[…]
    }
 
Plan: 1 to add, 0 to change, 2 to destroy.

You asked to remove one worker. Terraform plans to destroy two objects and create one. Read it carefully: web-c used to live at index 2; now it's at index 1, where web-b was. Terraform tracks instances by address, so it sees "the thing at [1] changed from web-b to web-c" (replace it) and "[2] no longer exists" (destroy it). The real web-c gets destroyed and recreated for no reason.

With local files that costs nothing. With servers it means web-c is rebuilt, loses its disk and its IP, and drops connections, all because of a list edit. This is the reason the rest of this tutorial mostly uses for_each.

for_each: one instance per key

for_each takes a map or a set of strings and creates one instance per element, addressed by key instead of position. Here are the same three workers in a fresh directory:

resource "local_file" "worker" {
  for_each = toset(var.workers)
 
  filename        = "${path.module}/out/${each.key}.conf"
  content         = "name=${each.value}\n"
  file_permission = "0644"
}
terraform apply -auto-approve
terraform state list
[…]
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
local_file.worker["web-a"]
local_file.worker["web-b"]
local_file.worker["web-c"]

Now remove web-b again:

terraform plan -var 'workers=["web-a","web-c"]'
[…]
  # local_file.worker["web-b"] will be destroyed
  # (because key ["web-b"] is not in for_each map)
  - resource "local_file" "worker" {
      - content              = <<-EOT
            name=web-b
        EOT -> null
[…]
    }
 
Plan: 0 to add, 0 to change, 1 to destroy.

Exactly one destroy, and the plan even says why. web-a and web-c keep their addresses, so nothing else moves. Inside a for_each block you get two values:

ExpressionFor a set of stringsFor a map
each.keyThe elementThe map key
each.valueThe same elementThe map value (often an object)

Note the toset(): for_each won't accept a list, because lists can contain duplicates and their order is meaningful. You'll see the error in Common mistakes.

for_each over a map of objects

Sets of strings are fine for names. Real services also have ports, replica counts and flags, so the usual shape is a map of objects keyed by name. Here's the platform team's configuration:

terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.5"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.6"
    }
  }
}
 
variable "services" {
  description = "Services run by the platform team, keyed by name"
  type = map(object({
    port     = number
    replicas = number
    public   = bool
  }))
  default = {
    checkout = { port = 8080, replicas = 3, public = true }
    cart     = { port = 8081, replicas = 2, public = true }
    search   = { port = 9200, replicas = 2, public = false }
  }
}
 
resource "local_file" "config" {
  for_each = var.services
 
  filename        = "${path.module}/out/${each.key}.json"
  file_permission = "0644"
  content = jsonencode({
    service  = each.key
    port     = each.value.port
    replicas = each.value.replicas
  })
}
 
resource "random_password" "db" {
  for_each = var.services
 
  length  = 20
  special = false
}
 
# Chained for_each: one secrets file per password, keyed the same way.
resource "local_sensitive_file" "db_env" {
  for_each = random_password.db
 
  filename = "${path.module}/out/${each.key}-db.env"
  content  = "DB_PASSWORD=${each.value.result}\n"
}
 
output "config_files" {
  value = { for name, f in local_file.config : name => f.filename }
}
 
output "public_services" {
  value = sort([for name, svc in var.services : name if svc.public])
}
terraform apply -auto-approve
[…]
local_sensitive_file.db_env["cart"]: Creation complete after 0s [id=3b447ccbef4368380804bfdd5c3836fb54920f5c]
local_sensitive_file.db_env["search"]: Creation complete after 0s [id=647d3820d28a903fd0ce6ca3df58f9f912c5d45d]
local_sensitive_file.db_env["checkout"]: Creation complete after 0s [id=485f4021098e8f6445a9c45a7f2e7a6d232d4f1c]
 
Apply complete! Resources: 9 added, 0 changed, 0 destroyed.
 
Outputs:
 
config_files = {
  "cart" = "./out/cart.json"
  "checkout" = "./out/checkout.json"
  "search" = "./out/search.json"
}
public_services = tolist([
  "cart",
  "checkout",
])
terraform state list
cat out/search.json
local_file.config["cart"]
local_file.config["checkout"]
local_file.config["search"]
local_sensitive_file.db_env["cart"]
local_sensitive_file.db_env["checkout"]
local_sensitive_file.db_env["search"]
random_password.db["cart"]
random_password.db["checkout"]
random_password.db["search"]
{"port":9200,"replicas":2,"service":"search"}

Three resource blocks, nine objects, all keyed by service name. Look at local_sensitive_file.db_env: its for_each is another resource, random_password.db, which is itself a map of instances. That's chaining. Each secrets file gets the same key as its password, and each.value is the whole password resource, so each.value.result is that service's password. Chaining keeps related resources in lockstep: add a service and both the password and its file appear; remove one and both go.

Turning lists into for_each input

Data often arrives as a list, from a variable, a file or another module. Two conversions cover almost every case:

  • A list of strings becomes a set with toset(var.workers), as above.
  • A list of objects becomes a map with a for expression, choosing a field that is unique as the key: { for s in var.service_list : s.name => s }.

The key you pick matters. It becomes part of every instance's address, so it should be stable (a name, not something that can change) and known at plan time (written in your configuration, not generated by another resource). Both rules have errors to go with them in Common mistakes.

Referencing instances

A resource with for_each is a map of instances; with count it's a list. These are the forms you'll use, evaluated against the services project:

> local_file.config["cart"].filename
"./out/cart.json"
> random_password.db["search"].length
20
> keys(local_file.config)
[
  "cart",
  "checkout",
  "search",
]
> values(local_file.config)[*].filename
[
  "./out/cart.json",
  "./out/checkout.json",
  "./out/search.json",
]
  • One instance: TYPE.NAME["key"].attribute (or [0] for count).
  • All instances as a map: { for k, r in TYPE.NAME : k => r.attribute }, as in the config_files output. This is usually the most useful shape for outputs, because callers can look things up by name.
  • All instances as a list: values(TYPE.NAME)[*].attribute. The plain splat TYPE.NAME[*] works only with count, because a for_each resource is a map.
  • Elsewhere in a for_each block: each.value when you chained, or other_resource[each.key] when two resources share keys.

Choosing between count and for_each

SituationUse
Instances have names or identities (servers, users, buckets, services)for_each
Instances differ in settingsfor_each over a map of objects
N truly identical, interchangeable copies, where any one can be removedcount
A resource that exists or doesn't, based on a flagcount = var.flag ? 1 : 0
The number comes from an input and nothing else distinguishes the copiescount

My rule: for_each unless the copies are genuinely fungible, and even then pause before using count on anything stateful. You can't use both on one resource. If you inherit a count-based resource, you can convert it to for_each without recreating anything by declaring moved blocks; Exercise 2 walks through it, and Terraform State covers refactoring in depth.

Conditional resources

The one place count is the idiomatic choice is a resource that should exist only sometimes. The platform team wants a nightly backup schedule, but only in environments that ask for it. I added this to the services project:

variable "enable_backups" {
  description = "Write a nightly backup schedule"
  type        = bool
  default     = false
}
 
resource "local_file" "backup_schedule" {
  count = var.enable_backups ? 1 : 0
 
  filename        = "${path.module}/out/backup.cron"
  file_permission = "0644"
  content         = "0 3 * * * /usr/local/bin/backup-db --all\n"
}
 
output "backup_schedule_file" {
  value = one(local_file.backup_schedule[*].filename)
}

With the default false, count is 0 and nothing is created. The output is null, and Terraform leaves null outputs out of its output list: when I applied the project with this block in place, only config_files and public_services were printed. Turn the flag on:

terraform plan -var enable_backups=true
[…]
  # local_file.backup_schedule[0] will be created
  + resource "local_file" "backup_schedule" {
      + content              = <<-EOT
            0 3 * * * /usr/local/bin/backup-db --all
        EOT
[…]
Plan: 1 to add, 0 to change, 0 to destroy.
 
Changes to Outputs:
  + backup_schedule_file = "./out/backup.cron"

The important detail is the output. Writing local_file.backup_schedule[0].filename fails when the resource is switched off, because there is no element 0. one() takes a list of zero or one elements and returns the element or null, so one(local_file.backup_schedule[*].filename) works in both states.

Dynamic blocks

count and for_each repeat whole resources. Sometimes you need to repeat a nested block inside one resource: the ingress rules of a security group, the source files of an archive. That's what a dynamic block does.

Locally, the archive provider's archive_file resource builds a zip from source blocks. To bundle every service's config into one deployable zip, I added archive to required_providers (source = "hashicorp/archive", version = "~> 2.4") and this resource:

resource "archive_file" "config_bundle" {
  type        = "zip"
  output_path = "${path.module}/out/config-bundle.zip"
 
  # One source block per service, generated from the same map.
  dynamic "source" {
    for_each = var.services
 
    content {
      filename = "${source.key}.json"
      content  = local_file.config[source.key].content
    }
  }
}

The anatomy:

  • dynamic "source" names the block type to generate.
  • for_each is the collection, exactly as for resources.
  • Inside content { … }, the iterator is named after the block: source.key and source.value, not each. (You can rename it with iterator = svc, useful when dynamic blocks are nested.)
terraform plan -var enable_backups=true
[…]
  # archive_file.config_bundle will be created
  + resource "archive_file" "config_bundle" {
[…]
      + output_path         = "./out/config-bundle.zip"
[…]
      + type                = "zip"
 
      + source {
          + content  = jsonencode(
                {
                  + port     = 8080
                  + replicas = 3
                  + service  = "checkout"
                }
            )
          + filename = "checkout.json"
        }
[…]
Plan: 1 to add, 0 to change, 0 to destroy.

After applying, the zip holds one file per service:

unzip -l out/config-bundle.zip
Archive:  out/config-bundle.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
       43  1980-00-00 00:00   cart.json
       47  1980-00-00 00:00   checkout.json
       45  1980-00-00 00:00   search.json
---------                     -------
      135                     3 files

The same on AWS: security group rules

The classic real-world dynamic block generates security group rules from a list:

variable "ingress_rules" {
  description = "Inbound rules for the checkout web tier"
  type = list(object({
    description = string
    port        = number
    cidr_blocks = list(string)
  }))
  default = [
    { description = "HTTPS from anywhere", port = 443, cidr_blocks = ["0.0.0.0/0"] },
    { description = "HTTP, redirected to HTTPS", port = 80, cidr_blocks = ["0.0.0.0/0"] },
    { description = "Node exporter from monitoring", port = 9100, cidr_blocks = ["10.20.8.0/24"] },
  ]
}
 
resource "aws_security_group" "web" {
  name        = "checkout-web"
  description = "Ingress for the checkout web tier"
  vpc_id      = var.vpc_id
 
  dynamic "ingress" {
    for_each = var.ingress_rules
 
    content {
      description = ingress.value.description
      from_port   = ingress.value.port
      to_port     = ingress.value.port
      protocol    = "tcp"
      cidr_blocks = ingress.value.cidr_blocks
    }
  }
 
  egress {
    description = "All outbound traffic"
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

The full configuration also declares the AWS provider (~> 6.0, region us-east-1) and a vpc_id variable with a placeholder default. It passed terraform validate, and a plan with the mock provider settings from Providers and Resources showed all three rules:

[…]
      + ingress                = [
          + {
              + cidr_blocks      = [
                  + "0.0.0.0/0",
                ]
              + description      = "HTTP, redirected to HTTPS"
              + from_port        = 80
[…]
          + {
              + cidr_blocks      = [
                  + "10.20.8.0/24",
                ]
              + description      = "Node exporter from monitoring"
              + from_port        = 9100
[…]
Plan: 1 to add, 0 to change, 0 to destroy.

A word of judgment: dynamic blocks hide structure, and a page of them is hard to review. Use them when the nested blocks really are data-driven. For security groups specifically, the AWS provider also offers one resource per rule, aws_vpc_security_group_ingress_rule, which pairs naturally with for_each:

resource "aws_vpc_security_group_ingress_rule" "api" {
  for_each = { for r in var.ingress_rules : r.port => r }
 
  security_group_id = aws_security_group.api.id
  description       = each.value.description
  from_port         = each.value.port
  to_port           = each.value.port
  ip_protocol       = "tcp"
  cidr_ipv4         = each.value.cidr_blocks[0]
}

I validated and planned that too (alongside an aws_security_group.api with no inline rules); it produced aws_vpc_security_group_ingress_rule.api["443"], ["80"] and ["9100"]. Each rule gets its own address, so adding or removing one rule is a one-resource change in the plan rather than an in-place edit of the whole group.

Where you'll use this

The services project above is the pattern in its real form: a map in a variables file is the inventory, and the configuration turns it into resources. On AWS the blocks would be ECR repositories, IAM roles, log groups and alarms per service, but the mechanics are identical. Onboarding the payments service is one line in platform.tfvars:

services = {
  checkout = { port = 8080, replicas = 3, public = true }
  cart     = { port = 8081, replicas = 2, public = true }
  search   = { port = 9200, replicas = 2, public = false }
  payments = { port = 8090, replicas = 2, public = false }
}
 
enable_backups = true
terraform plan -var-file=platform.tfvars | grep -E '^  # |^Plan|forces replacement'
  # archive_file.config_bundle must be replaced
      + source { # forces replacement
  # local_file.config["payments"] will be created
  # local_sensitive_file.db_env["payments"] will be created
  # random_password.db["payments"] will be created
Plan: 4 to add, 0 to change, 1 to destroy.

Every resource for the new service appears, keyed by its name, and the existing services are untouched. The one replacement is expected: the bundle's contents changed. A reviewer can approve that pull request in seconds, which is the whole point. Other everyday uses:

  • Feature flags per environment: count = var.enable_x ? 1 : 0 for things like a bastion host in dev only, or a WAF in production only.
  • Per-team access: a map of team names to members, turned into groups and memberships with for_each (Exercise 3 builds a small version).
  • Firewall and routing rules: lists of rules rendered with dynamic blocks or per-rule resources.

Common mistakes

Passing a list to for_each

resource "local_file" "worker" {
  for_each = var.workers
  filename = "${path.module}/out/${each.key}.conf"
  content  = "name=${each.value}\n"
}
╷
│ Error: Invalid for_each argument
│ 
│   on m.tf line 2, in resource "local_file" "worker":
│    2:   for_each = var.workers
│     ├────────────────
│     │ var.workers is a list of string
│ 
│ The given "for_each" argument value is unsuitable: the "for_each" argument
│ must be a map, or set of strings, and you have provided a value of type
│ list of string.
╵

Wrap it: for_each = toset(var.workers). For a list of objects, build a map with a for expression instead.

Keys that are only known after apply

Here the keys come from a resource that doesn't exist yet:

resource "random_pet" "env" {}
 
resource "local_file" "marker" {
  for_each = toset([random_pet.env.id])
  filename = "${path.module}/out/${each.key}.txt"
  content  = "created for ${each.key}\n"
}

validate passes, but plan can't work out the instance addresses:

[…]
│ Error: Invalid for_each argument
│ 
│   on m.tf line 4, in resource "local_file" "marker":
│    4:   for_each = toset([random_pet.env.id])
│     ├────────────────
│     │ random_pet.env.id is a string, known only after apply
│ 
│ The "for_each" set includes values derived from resource attributes that
│ cannot be determined until apply, and so Terraform cannot determine the
│ full set of keys that will identify the instances of this resource.
│ 
│ When working with unknown values in for_each, it's better to use a map
│ value where the keys are defined statically in your configuration and where
│ only the values contain apply-time results.
[…]

The message gives the real fix: keys from your configuration ("primary" = random_pet.env.id), values from resources. Unknown values are fine; unknown keys are not. The same applies to count: it must be known at plan time.

Indexing a resource that's switched off

Referencing local_file.backup_schedule[0].filename directly while enable_backups is false:

╷
│ Error: Invalid index
│ 
│   on m.tf line 13, in output "backup_schedule_file":
│   13:   value = local_file.backup_schedule[0].filename
│     ├────────────────
│     │ local_file.backup_schedule is empty tuple
│ 
│ The given key does not identify an element in this collection value: the
│ collection has no elements.
╵

Use one(local_file.backup_schedule[*].filename), as shown in Conditional resources.

Duplicate keys in a for expression

Building a map from a list of users keyed by team, when two users share a team:

locals {
  users_by_team = { for u in var.users : u.team => u.name }
}
╷
│ Error: Duplicate object key
│ 
│   on m.tf line 11, in locals:
│   11:   users_by_team = { for u in var.users : u.team => u.name }
│     ├────────────────
│     │ u.team is "payments"
│ 
│ Two different items produced the key "payments" in this 'for' expression.
│ If duplicates are expected, use the ellipsis (...) after the value
│ expression to enable grouping by key.
╵

If the key should be unique, the data is wrong; fix the data, or pick a key that's actually unique. If grouping is what you want, add ... after the value (u.team => u.name...) and each key maps to a list of names. Exercise 3 uses exactly that.

Using count and for_each together

╷
│ Error: Invalid combination of "count" and "for_each"
│ 
│   on m.tf line 3, in resource "local_file" "both":
│    3:   for_each = toset(var.workers)
│ 
│ The "count" and "for_each" meta-arguments are mutually-exclusive, only one
│ should be used to be explicit about the number of resources to be created.
╵

To make a for_each resource conditional, filter the collection instead: for_each = var.enabled ? var.services : {}.

Summary

  • count = N creates N instances addressed [0], [1], …; for_each creates one instance per map key or set element, addressed ["key"].
  • count tracks instances by position, so removing an item from the middle of a list replaces or destroys every instance after it. for_each destroys only the removed key.
  • for_each accepts maps and sets of strings: convert lists with toset() or a { for x in list : x.name => x } expression, and choose keys that are stable and known at plan time.
  • Inside for_each, use each.key and each.value; chaining (for_each = other_resource) keeps related resources keyed identically.
  • Reference instances as res["key"], collect them with { for k, r in res : k => r.attr } or values(res)[*].attr; splat res[*] only works with count.
  • count = var.flag ? 1 : 0 makes a resource conditional; read it safely with one(res[*].attr).
  • dynamic "BLOCK" generates repeated nested blocks; the iterator is named after the block (ingress.value). Use it for genuinely data-driven blocks, and prefer per-item resources where the provider offers them.

Exercises

Exercise 1: One file per environmenteasy

Create a configuration with a set(string) variable environments defaulting to ["dev", "staging", "prod"] and a local_file per environment at out/env-NAME.txt containing environment=NAME. Apply it, list the state, then plan the removal of staging.

Show Solution
variable "environments" {
  type    = set(string)
  default = ["dev", "staging", "prod"]
}
 
resource "local_file" "marker" {
  for_each = var.environments
 
  filename        = "${path.module}/out/env-${each.key}.txt"
  content         = "environment=${each.value}\n"
  file_permission = "0644"
}

(Plus the usual required_providers block for hashicorp/local.)

terraform apply -auto-approve
terraform state list
terraform plan -var 'environments=["dev","prod"]' | grep -E '^  # |^Plan'
[…]
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
local_file.marker["dev"]
local_file.marker["prod"]
local_file.marker["staging"]
  # local_file.marker["staging"] will be destroyed
  # (because key ["staging"] is not in for_each map)
Plan: 0 to add, 0 to change, 1 to destroy.

Because the variable's type is already set(string), no toset() is needed.

Exercise 2: Migrate count to for_each without recreating anythingmedium

Start from the count-based workers configuration at the top of this tutorial, applied. Convert it to for_each so that the plan shows 0 to add, 0 to change, 0 to destroy. Keep the file contents identical, including the slot= line.

Hint

A moved block tells Terraform that an object has a new address: moved { from = OLD_ADDRESS to = NEW_ADDRESS }. For the content, index(list, value) returns an element's position.

Show Solution
resource "local_file" "worker" {
  for_each = toset(var.workers)
 
  filename        = "${path.module}/out/${each.key}.conf"
  content         = "name=${each.key}\nslot=${index(var.workers, each.key)}\n"
  file_permission = "0644"
}
 
moved {
  from = local_file.worker[0]
  to   = local_file.worker["web-a"]
}
 
moved {
  from = local_file.worker[1]
  to   = local_file.worker["web-b"]
}
 
moved {
  from = local_file.worker[2]
  to   = local_file.worker["web-c"]
}
 
output "worker_files" {
  value = [for w in var.workers : local_file.worker[w].filename]
}
terraform plan
[…]
  # local_file.worker[0] has moved to local_file.worker["web-a"]
    resource "local_file" "worker" {
        id                   = "346706bba73b15e4f5cb6656296368a013784829"
        # (10 unchanged attributes hidden)
    }
 
  # local_file.worker[1] has moved to local_file.worker["web-b"]
[…]
  # local_file.worker[2] has moved to local_file.worker["web-c"]
[…]
Plan: 0 to add, 0 to change, 0 to destroy.

After apply, terraform state list shows the three ["web-…"] addresses and the same file IDs as before. The output had to change too: local_file.worker[*] no longer works on a for_each resource.

Exercise 3: Team files from a list of usersmedium

Given a list of users with name and team (asha and chen in payments, bruno in search, dana in platform), create one file per team at out/teams/TEAM.txt listing its members alphabetically, one per line.

Hint

You need a map from team to a list of names. That's a for expression with the grouping ... from Common mistakes.

Show Solution
variable "users" {
  type = list(object({ name = string, team = string }))
  default = [
    { name = "asha", team = "payments" },
    { name = "bruno", team = "search" },
    { name = "chen", team = "payments" },
    { name = "dana", team = "platform" },
  ]
}
 
locals {
  # The ellipsis groups duplicate keys into lists.
  members_by_team = { for u in var.users : u.team => u.name... }
}
 
resource "local_file" "team" {
  for_each = local.members_by_team
 
  filename        = "${path.module}/out/teams/${each.key}.txt"
  content         = "${join("\n", sort(each.value))}\n"
  file_permission = "0644"
}
terraform apply -auto-approve
head out/teams/*.txt
[…]
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
==> out/teams/payments.txt <==
asha
chen
 
==> out/teams/platform.txt <==
dana
 
==> out/teams/search.txt <==
bruno

Three teams, three files; adding a user to an existing team updates one file instead of creating anything.

Exercise 4: Ingress only for public serviceshard

Using the services map from this tutorial, write an aws_security_group whose ingress rules are generated only for services with public = true, each opening that service's port with the description "NAME service". Validate it and confirm with a mocked plan that search gets no rule.

Show Solution
resource "aws_security_group" "public_services" {
  name        = "public-services"
  description = "Ingress for services exposed to the internet"
  vpc_id      = "vpc-0a1b2c3d4e5f60718"
 
  dynamic "ingress" {
    for_each = { for name, svc in var.services : name => svc if svc.public }
 
    content {
      description = "${ingress.key} service"
      from_port   = ingress.value.port
      to_port     = ingress.value.port
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }
}

With the aws provider block and the same mock_override.tf as in Providers and Resources:

terraform validate
terraform plan -input=false | grep -E 'description|from_port|^Plan'
Success! The configuration is valid.
 
      + description            = "Ingress for services exposed to the internet"
              + description      = "cart service"
              + from_port        = 8081
              + description      = "checkout service"
              + from_port        = 8080
Plan: 1 to add, 0 to change, 0 to destroy.

The filter lives in the for_each expression (if svc.public), so the dynamic block itself stays simple. Port 9200 never appears.


Tested with: Terraform v1.17.1 on Ubuntu 24.04 (WSL2, linux_amd64), November 2026, with hashicorp/local v2.9.1, hashicorp/random v3.9.1, hashicorp/archive v2.8.1 and hashicorp/aws v6.72.0. All local configurations were applied and every output is from a real run, trimmed where marked […]; IDs and passwords will differ on your machine. The AWS security group configurations were run through init, validate and terraform plan with mock provider credentials only; nothing was created in AWS.

Was this page helpful?
The Dark Debugger

Written by The Dark Debugger

Engineer documenting the things that took me too long to learn, so they take you less time. Every Terraform tutorial here is tested end to end before publishing.