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

Members can save this page, take notes and track progress. See membership · Sign in

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/.

One map in, one resource instance per key outvar.environments (map)devt3.micro × 1, debugstagingt3.small × 2prodt3.large × 3for_eacheach.key, each.valuelocal_file.env["dev"]one instanceout/dev.envlocal_file.env["staging"]one instanceout/staging.envlocal_file.env["prod"]one instanceout/prod.env
for_each turns a map into one resource instance per key, addressed by the key

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

Download starter filesDownload finished project

Steps

  1. 1Pin the provider

    versions.tf
    terraform {
      required_version = ">= 1.6"
    
      required_providers {
        local = {
          source  = "hashicorp/local"
          version = "~> 2.5"
        }
      }
    }
    
  2. 2Model environments as a typed map

    One variable holds every environment. The object type documents exactly what each entry needs, optional(bool, false) gives debug a default, and the validation checks every entry at once with alltrue and a for expression.

    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."
      }
    }
    
  3. 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, so main.tf stays 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])
    }
    
  4. 4Create one resource per environment

    for_each creates one local_file per map key. Inside the block, each.key is the environment name and each.value its 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
    }
    
  5. 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
    }
    
  6. 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 plan
    

    Expected 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             = 6
    Check:

    Plan: 3 to add and total_replicas = 6.

  7. 7Apply and look at the files

    Run
    terraform apply
    ls out
    cat out/staging.env
    

    Expected 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.

  8. 8Try expressions in the console

    terraform console evaluates expressions against your configuration and state. It's the fastest way to get a for expression right before you put it in code. Type each line, then exit.

    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",
    ]
  9. 9Remove one environment

    smaller.tfvars holds 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 }
    }
    
  10. 10Plan with the smaller map

    Run
    terraform plan -var-file=smaller.tfvars
    

    Expected 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.

  11. 11Compare with count

    count-demo/ creates three files from a list with count. 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 web disappears, api moves from [1] to [0] and worker from [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: removing staging destroys exactly local_file.env["staging"] and leaves dev and prod untouched. Keep count for "zero or one" (count = var.enabled ? 1 : 0) or truly identical copies.

    count: remove web from the listfor_each: remove staging from the mapBeforeAfterBeforeAfter[0] web[0] apiwas web: replaced[1] api[1] workerwas api: replaced[2] worker[2]destroyed["dev"]["dev"]unchanged["staging"]["staging"]destroyed["prod"]["prod"]unchangedItems are addressed by position: everything after shiftsItems are addressed by key: only the removed one changes
    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]
    }
    
  12. 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.

  13. 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.
  14. 14Destroy both projects

    Run
    terraform destroy
    cd count-demo && terraform destroy
    

    Expected 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_each with a map or set whenever items have a natural name (environments, zones, users). Adding or removing one item never disturbs the others.
  • Use count only for "N identical copies" (count = var.replicas) or for an on/off switch (count = var.enabled ? 1 : 0).
  • Moving from count to for_each on live resources? Add moved blocks so Terraform renames them instead of replacing them.

Production checklist

  • Collections of named things use for_each with stable keys, never list positions
  • Complex inputs have an object type, optional() defaults and validation
  • 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

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake