Lesson 3 of 8 · 11 min · Writing configuration
Variables, locals, outputs and loops
What you will learn
- Input variables: types, defaults, validation, sensitive values, how to supply them
- Locals and expressions: interpolation,
forexpressions, functions - Outputs and how other code consumes them
countversusfor_each, and whyfor_eachis usually safer- Conditional expressions and
dynamicblocks
In simple words
Writing the same code three times for dev, test and production is wasteful and risky. Variables let one piece of code take different values, like a form with blanks to fill in. Loops let you say "make five of these" once. Outputs show you useful results, such as a server's address.
Words to know
- Variable: a value passed into your Terraform code, such as the environment name.
- Local: a named value worked out inside the code, so it isn't repeated.
- Output: a value Terraform prints or passes on after it runs.
- for_each: creates one copy of a resource for each item in a list or map.
Input variables
Variables make a configuration reusable across environments.
variable "environment" {
type = string
description = "Deployment environment"
default = "dev"
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "environment must be dev, staging or prod."
}
}
type:string,number,bool,list(string),set(string),map(string),object({ ... }),tuple, orany. Always declare types: they catch mistakes early.default: optional. A variable without one is required; Terraform asks for it (or fails in automation).validation: custom checks with a clear message. With an invalid value:
Error: Invalid value for variable
environment must be dev, staging or prod.
Validation runs at plan time, before anything is created.
Supplying values (in increasing precedence)
- defaults in the code,
terraform.tfvarsand*.auto.tfvars(loaded automatically),-var-file=prod.tfvars,- environment variables
TF_VAR_name(handy in CI), -var 'name=value'on the command line.
A common layout is one file per environment: terraform plan -var-file=envs/prod.tfvars.
Sensitive values
variable "db_password" {
type = string
sensitive = true
}
sensitive = true hides the value in plan and apply output ((sensitive value)) and in terraform output, and Terraform requires dependent outputs to be marked sensitive too (we hit this error: "Output refers to sensitive values"). But sensitive values are still stored in clear text in the state file. We proved it by grepping our local state, which contained password=s3cr3t, while plan printed content = (sensitive value). Consequences: protect the state like a secret (encrypted remote backend, restricted access), never commit it, and prefer to avoid having secrets in Terraform at all: let the cloud generate the password and store it in a secrets manager (for example RDS manage_master_user_password), or pass only the secret's name. Newer Terraform versions add write-only arguments and ephemeral values for some secrets, which keep them out of state: use them when the provider supports them.
Locals, expressions and functions
Locals name intermediate values so you do not repeat yourself:
locals {
tags = {
Project = "shop"
Environment = var.environment
ManagedBy = "terraform"
}
name_prefix = "shop-${var.environment}"
}
Use local.tags. Expressions:
- Interpolation:
"${var.environment}-${random_pet.name.id}". - Conditionals:
var.environment == "prod" ? 3 : 1. forexpressions build lists and maps:[for s in var.names : upper(s)],{ for k, v in local.services : k => v.port }.- Functions:
merge(a, b),join(",", list),lookup(map, key, default),length(),contains(),toset(),cidrsubnet(prefix, newbits, index)(computes subnets!),file(),templatefile(),jsonencode(). Try them interraform console. Example:cidrsubnet("10.0.0.0/16", 8, 1)returns10.0.1.0/24.
Outputs
output "vpc_id" {
value = aws_vpc.main.id
description = "ID of the main VPC"
}
output "subnet_ids" {
value = { for k, s in aws_subnet.public : k => s.id }
}
Outputs print after apply, can be read with terraform output -json by scripts and pipelines, are how a module returns values to its caller, and how other stacks read this one's results (terraform_remote_state or a parameter store). Mark secret ones sensitive = true.
Creating many resources: count and for_each
count creates N copies, addressed by index:
resource "local_file" "nodes" {
count = 2
filename = "${path.module}/out/node-${count.index}.txt"
content = "node ${count.index}\n"
}
State addresses: local_file.nodes[0], local_file.nodes[1]. It is good for "N identical things" and for on/off switches (count = var.enabled ? 1 : 0).
The count trap: if you build the copies from a list and remove an item from the middle, every later element's index shifts, and Terraform plans to modify or destroy-and-recreate the ones that follow. We saw it: reducing count from 2 to 1 planned local_file.count_demo[1] will be destroyed; with a list of names, deleting "b" from ["a","b","c"] makes c become index 1, so b's resource is "changed" into c and the old c destroyed.
for_each keys each instance by a stable string, from a map or a set:
locals {
services = {
web = { port = "80", replicas = "3" }
api = { port = "8080", replicas = "2" }
}
}
module "service_conf" {
source = "./modules/config_file"
for_each = local.services
name = each.key
settings = each.value
dir = "${path.module}/out"
}
Addresses are module.service_conf["web"] and module.service_conf["api"]. Removing api from the map destroyed only that one:
# module.service_conf["api"].local_file.this will be destroyed
Plan: 0 to add, 0 to change, 1 to destroy.
Rule of thumb: use for_each with a map or set of stable keys; use count only for identical copies or a 0/1 toggle. Limitation: for_each keys must be known at plan time (not computed from resources not yet created).
Both count and for_each work on modules too (as above) and give you count.index/each.key/each.value. Resources created this way are referenced as lists/maps: aws_subnet.public["a"].id, or [for s in aws_subnet.public : s.id] for all.
dynamic blocks
When a nested block repeats depending on data (many ingress rules in a security group):
variable "ingress_ports" {
type = list(number)
default = [80, 443]
}
resource "aws_security_group" "web" {
name = "web"
vpc_id = aws_vpc.main.id
dynamic "ingress" {
for_each = var.ingress_ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
}
Use it when needed; plain repeated blocks are easier to read for two or three rules.
Practical rules
- Variables for what differs between environments; locals for what is derived; outputs for what others need.
- Keep
variables.tf,outputs.tfandmain.tftidy; document every variable and output. - Don't over-parameterise: every variable is a decision someone must make.
- Use
terraform consoleto experiment with expressions, andterraform validateto catch mistakes. - Keep secrets out of
.tfvarsfiles in Git (use environment variables or a secrets manager).
Common mistakes
- Untyped variables and silent conversions.
countover lists that change in the middle.- Believing
sensitive = trueencrypts anything. - Putting secrets in committed
.tfvarsfiles. - Over-clever expressions nobody can read.
- A required variable with no value in CI, failing at the prompt.
- Computing
for_eachkeys from resources that don't exist yet.
Try it yourself
- Add a validated
environmentvariable and test an invalid value. - Use
terraform consoleto evaluatecidrsubnet("10.0.0.0/16", 8, 3)and aforexpression over a map. - Create three resources with
countfrom a list, remove the middle item and read the plan; then redo it withfor_each. - Make an output sensitive and see how
terraform outputshows it.
Check yourself
Why is for_each usually preferred over count for lists of things?
for_each identifies instances by stable keys, so adding or removing one affects only that instance. With count, removing a middle item shifts the indices and Terraform changes or recreates the following resources.
Does sensitive = true protect a secret in the state file?
No. It only hides the value in CLI output. The state still stores it in plain text, so state storage must be encrypted and access-controlled, or secrets kept out of Terraform.
How do you give a variable a different value per environment?
With separate -var-file files (dev.tfvars, prod.tfvars), TF_VAR_ environment variables or CI-provided values.
What is a local value for?
Naming an intermediate expression (common tags, name prefixes) so it is computed once and reused, reducing repetition.
Interview questions
How would you create one subnet per availability zone without repeating code?
Use for_each over a map of zone → CIDR (or toset(data.aws_availability_zones.available.names) with cidrsubnet() for ranges), referencing each.key and each.value.
How do you handle secrets such as database passwords in Terraform?
Avoid storing them: have the platform generate and store them (secrets manager integration), pass only references, mark variables sensitive, keep state encrypted and restricted, and never commit tfvars with secrets.
What does count = var.enabled ? 1 : 0 do?
Makes a resource optional: one instance when enabled, none otherwise. Refer to it with an index (resource.x[0]) or one(resource.x[*].id).
Summary
- Variables parameterise (typed, validated, supplied by tfvars/env/CLI); locals derive; outputs export.
sensitivehides values in output but not in state: protect state, avoid secrets in Terraform.- Prefer
for_eachwith stable keys tocountover lists; usedynamicblocks sparingly. - Test expressions in
terraform console.
Going deeper
- Input variables: types, validation, sensitivity and precedence.
- Local values and outputs: reference pages.
- The for_each meta-argument and count: behaviour and limitations.
- Built-in functions: the complete function list.
- Manage sensitive data: sensitive values and state.
See how much of this you can explain
A free mock interview asks you new questions on Infrastructure as Code with Terraform for DevOps Engineer and scores every answer, with what to fix.