Terraform Labs · Lab 2 of 9
Variables, Locals and for_each: One Config per Environment
Describe every environment in one typed map variable, generate a file per environment with for_each, compute values with for expressions, and see why removing one environment with for_each touches only that one — while count shifts everything after it.
- Environment
- Local
- Level
- Beginner
- Time
- About 40 min
- Cost
- Free
You will build
A project that turns one environments map into a config file per environment, plus a clear picture of when
to use for_each and when count is risky.
Before you start
- Lab: Your First Terraform Project: Plan, Apply, Destroy
Terraform 1.6 or newer
Real projects rarely create one of something. You'll model dev, staging and prod as data, then let Terraform create one resource per entry. The same pattern later creates one subnet per availability zone, one bucket per team or one DNS record per service.
How for_each works here
var.environments is a map with one entry per environment. for_each loops over it and creates one
instance of local_file.env per key: inside the block, each.key is the name (dev) and each.value is
that entry's settings. Each instance is addressed by its key, such as local_file.env["dev"], and writes its
own file under out/.
Project structure
env-configs/
├── .gitignore
├── versions.tf
├── variables.tf # typed map of environments, with validation
├── locals.tf # values computed with for expressions
├── main.tf # one local_file per environment (for_each)
├── outputs.tf
├── smaller.tfvars # the same map without staging
└── count-demo/
└── main.tf # the same idea with count, to compare
Steps
-
1Pin the provider
versions.tf terraform { required_version = ">= 1.6" required_providers { local = { source = "hashicorp/local" version = "~> 2.5" } } } -
2Model environments as a typed map
One variable holds every environment. The
objecttype documents exactly what each entry needs,optional(bool, false)givesdebuga default, and thevalidationchecks every entry at once withalltrueand aforexpression.variables.tf variable "project" { description = "Project name, written into every file" type = string default = "shop" } variable "environments" { description = "Settings for each environment, keyed by environment name" type = map(object({ instance_type = string replicas = number debug = optional(bool, false) })) default = { dev = { instance_type = "t3.micro", replicas = 1, debug = true } staging = { instance_type = "t3.small", replicas = 2 } prod = { instance_type = "t3.large", replicas = 3 } } validation { condition = alltrue([for env in values(var.environments) : env.replicas >= 1 && env.replicas <= 10]) error_message = "Every environment needs between 1 and 10 replicas." } } -
3Compute values with for expressions
[for name, env in map : name if condition]filters a map into a list. Locals keep this logic out of resources, somain.tfstays easy to read.locals.tf locals { # Environments that run more than one replica, e.g. for rolling deploys multi_replica = [for name, env in var.environments : name if env.replicas > 1] total_replicas = sum([for env in values(var.environments) : env.replicas]) } -
4Create one resource per environment
for_eachcreates onelocal_fileper map key. Inside the block,each.keyis the environment name andeach.valueits settings.main.tf resource "local_file" "env" { for_each = var.environments filename = "${path.module}/out/${each.key}.env" content = <<-EOT PROJECT=${var.project} ENVIRONMENT=${each.key} INSTANCE_TYPE=${each.value.instance_type} REPLICAS=${each.value.replicas} DEBUG=${each.value.debug} EOT } -
5Expose the results
outputs.tf output "files" { description = "Generated file for each environment" value = { for name, f in local_file.env : name => f.filename } } output "multi_replica_environments" { value = local.multi_replica } output "total_replicas" { value = local.total_replicas } -
6Plan: one resource per key
Each instance is addressed by its key, such as
local_file.env["prod"]— not by a number.Run terraform init terraform planExpected output
# local_file.env["dev"] will be created + resource "local_file" "env" { + content = <<-EOT PROJECT=shop ENVIRONMENT=dev INSTANCE_TYPE=t3.micro REPLICAS=1 DEBUG=true EOT + filename = "./out/dev.env" ... } # local_file.env["prod"] will be created ... # local_file.env["staging"] will be created ... Plan: 3 to add, 0 to change, 0 to destroy. Changes to Outputs: + files = { + dev = "./out/dev.env" + prod = "./out/prod.env" + staging = "./out/staging.env" } + multi_replica_environments = [ + "prod", + "staging", ] + total_replicas = 6Check:Plan: 3 to addandtotal_replicas = 6. -
7Apply and look at the files
Run terraform apply ls out cat out/staging.envExpected output
Apply complete! Resources: 3 added, 0 changed, 0 destroyed. ... dev.env prod.env staging.env PROJECT=shop ENVIRONMENT=staging INSTANCE_TYPE=t3.small REPLICAS=2 DEBUG=false
Check:Staging shows
DEBUG=false: the optional attribute fell back to its default. -
8Try expressions in the console
terraform consoleevaluates expressions against your configuration and state. It's the fastest way to get aforexpression right before you put it in code. Type each line, thenexit.Run terraform console > local.multi_replica > var.environments["staging"].debug > [for name, env in var.environments : "${name}=${env.replicas}"]Expected output
[ "prod", "staging", ] false [ "dev=1", "prod=3", "staging=2", ]
-
9Remove one environment
smaller.tfvarsholds the same map without staging. Because instances are keyed by name, Terraform destroys only staging; dev and prod are untouched.smaller.tfvars environments = { dev = { instance_type = "t3.micro", replicas = 1, debug = true } prod = { instance_type = "t3.large", replicas = 3 } } -
10Plan with the smaller map
Run terraform plan -var-file=smaller.tfvarsExpected output
# local_file.env["staging"] will be destroyed # (because key ["staging"] is not in for_each map) - resource "local_file" "env" { ... - filename = "./out/staging.env" -> null } Plan: 0 to add, 0 to change, 1 to destroy.Check:Only
local_file.env["staging"]is in the plan. -
11Compare with count
count-demo/creates three files from a list withcount. Instances are numbered[0],[1],[2], so removing the first name shifts every later one down by one position.Both panels remove one item. With count (left), instances are numbered: when
webdisappears,apimoves from[1]to[0]andworkerfrom[2]to[1], so Terraform sees different content at every later position, replaces those files and destroys the now-unused[2]. With for_each (right), instances are named: removingstagingdestroys exactlylocal_file.env["staging"]and leavesdevandproduntouched. Keepcountfor "zero or one" (count = var.enabled ? 1 : 0) or truly identical copies.count addresses instances by position, for_each by key: what one removal does to each count-demo/main.tf terraform { required_providers { local = { source = "hashicorp/local" version = "~> 2.5" } } } variable "names" { type = list(string) default = ["web", "api", "worker"] } resource "local_file" "server" { count = length(var.names) filename = "${path.module}/out/server-${count.index}.txt" content = var.names[count.index] } -
12Watch count shift everything
Run cd count-demo terraform init terraform apply terraform plan -var='names=["api","worker"]'Expected output
Apply complete! Resources: 3 added, 0 changed, 0 destroyed. ... # local_file.server[0] must be replaced ~ content = "web" -> "api" # forces replacement ... # local_file.server[1] must be replaced ~ content = "api" -> "worker" # forces replacement ... # local_file.server[2] will be destroyed # (because index [2] is out of range for count) ... Plan: 2 to add, 0 to change, 3 to destroy.Check:Removing one name destroys three resources. With real servers or databases that would be an outage.
-
13Catch bad input early
Run cd .. terraform plan -var 'environments={dev={instance_type="t3.micro",replicas=0}}'Expected output
Error: Invalid value for variable on variables.tf line 7: 7: variable "environments" { ├──────────────── │ var.environments is map of object with 1 element Every environment needs between 1 and 10 replicas. -
14Destroy both projects
Run terraform destroy cd count-demo && terraform destroyExpected output
Destroy complete! Resources: 3 destroyed. Destroy complete! Resources: 3 destroyed.
In production
What changes
| In this lab | In production |
|---|---|
| A map of environments in one root module | Usually one root (folder and state) per environment; the map pattern is used inside an environment, e.g. one subnet per zone or one bucket per team |
| Defaults hold the data | Data lives in terraform.tfvars per environment, reviewed in pull requests like code |
local_file resources |
Subnets, buckets, DNS records, IAM users — anything you have several of |
| Removing a key destroys a resource silently after apply | Plans are reviewed in CI; destroys of stateful resources are blocked with lifecycle { prevent_destroy = true } |
for_each or count?
- Use
for_eachwith a map or set whenever items have a natural name (environments, zones, users). Adding or removing one item never disturbs the others. - Use
countonly for "N identical copies" (count = var.replicas) or for an on/off switch (count = var.enabled ? 1 : 0). - Moving from
counttofor_eachon live resources? Addmovedblocks so Terraform renames them instead of replacing them.
Production checklist
- Collections of named things use
for_eachwith stable keys, never list positions - Complex inputs have an
objecttype,optional()defaults andvalidation - Logic lives in
locals, resources stay declarative - Stateful resources (databases, buckets with data) have
prevent_destroy - Every plan that destroys something is read before it's applied
Learn the concepts
- Terraform Variables · Terraform Tutorial
- Terraform Locals · Terraform Tutorial
- Terraform count and for_each · Terraform Tutorial
- Terraform for Expressions · Terraform Tutorial
- Terraform Types · Terraform Tutorial
- Terraform in Production · Course
Preparing for the Terraform Associate exam? Practice tests and mock exams →