Variables, locals and outputs
Make configurations reusable with typed variables and validation, .tfvars files, locals and outputs, and catch bad assumptions with preconditions.
By the end of this lesson you'll be able to
0 of 5 completeVerified lab: the validation error, -var-file plan, outputs and the failing precondition. Run on Terraform 1.17.1; the output shown is real.
Code walkthrough: the postcondition and check block examples: explained, not run.
Cloud lab: none; nothing here needs a cloud account.
Hard-coded values make a configuration good for exactly one thing. Variables turn it into something you can run for dev and prod, for any team, without copying files. Think of a configuration as a function: variables are its parameters, locals are its internal variables, outputs are its return values.
Input variables
# variables.tf variable "env" { description = "Environment name: dev, staging or prod." type = string validation { condition = contains(["dev", "staging", "prod"], var.env) error_message = "env must be dev, staging or prod." } } variable "servers" { description = "Server name => size." type = map(string) default = { web = "t3.micro" api = "t3.small" } } variable "replicas" { description = "How many worker files to create." type = number default = 2 }
Each argument earns its place:
typemakes Terraform reject the wrong shape early: a string where a number belongs, a list where a map belongs.defaultmakes the variable optional.envhas none, so it's required and Terraform asks for it (or fails in CI).descriptionshows up in docs and prompts. Write it for the next person.validationchecks the value with your own rule and message. You can have several.- Also available:
sensitive = true(hide the value in output, see the Security lesson) andnullable = false.
Use it anywhere in the module as var.env. Here's validation stopping a typo before anything is
planned:
$ terraform plan -var="env=test" Planning failed. Terraform encountered an error while generating this plan. Error: Invalid value for variable on variables.tf line 1: 1: variable "env" { ├──────────────── │ var.env is "test" env must be dev, staging or prod. This was checked by the validation rule at variables.tf:5,3-13.
terraform plan -var="env=test"terraforminfrastructure as codeplanpreview changes
tfvars files
Typing -var for every value doesn't scale. Put the values for one environment in a .tfvars
file:
# dev.tfvars env = "dev" replicas = 1
$ terraform plan -var-file=dev.tfvars
terraform plan -var-file=dev.tfvarsterraforminfrastructure as codeplanpreview changes
Terraform also loads two kinds of files automatically, with no flag: terraform.tfvars and any
*.auto.tfvars. When the same variable is set in several places, the later one in this list wins:
- The
defaultin the variable block - Environment variables named
TF_VAR_<name>, such asTF_VAR_env=dev terraform.tfvars, thenterraform.tfvars.json*.auto.tfvarsfiles, in alphabetical order-varand-var-fileon the command line, in the order you wrote them
A common setup: dev.tfvars, staging.tfvars and prod.tfvars in Git, and CI passing the right
one with -var-file. Keep secrets out of tfvars files; TF_VAR_ variables set by CI from its secret
store are the usual way in.
Locals
# main.tf locals { prefix = "shop-${var.env}" common = "managed-by: terraform\nenv: ${var.env}\n" }
A local names an expression so you write it once. Every file name in this project uses
local.prefix, so renaming the scheme is a one-line change. Unlike variables, locals can't be set
from outside, which is the point: they're for values derived inside the module.
Good uses: name prefixes, merged tag maps (merge(var.tags, { env = var.env })), and values computed
from several variables. A local used only once is just indirection; inline it.
Outputs
# outputs.tf output "server_files" { description = "File created for each server." value = { for k, f in local_file.server : k => f.filename } } output "worker_count" { value = length(local_file.worker) }
After apply, Terraform prints outputs, and you can read them any time:
$ terraform output server_files = { "api" = "./out/shop-dev-api.txt" "web" = "./out/shop-dev-web.txt" } worker_count = 1 $ terraform output -json server_files {"api":"./out/shop-dev-api.txt","web":"./out/shop-dev-web.txt"}
terraform outputterraforminfrastructure as code
Outputs have three audiences: people (the load balancer URL after apply), scripts and CI
(terraform output -raw url in a deploy step), and other configurations (module outputs in
lesson 10, remote state in lesson 15). Only output what someone needs; every output is a contract.
Preconditions and postconditions
Validation can only look at one variable. A precondition checks any assumption before Terraform plans or applies a resource, such as a relationship between variables or a data source's result:
resource "local_file" "summary" { filename = "${path.module}/out/${local.prefix}-summary.txt" content = join("\n", [for k, f in local_file.server : "${k}: ${f.filename}"]) lifecycle { precondition { condition = length(var.servers) > 0 error_message = "Define at least one server." } } }
$ terraform plan -var-file=dev.tfvars -var='servers={}' Error: Resource precondition failed on main.tf line 28, in resource "local_file" "summary": 28: condition = length(var.servers) > 0 ├──────────────── │ var.servers is empty map of string Define at least one server.
terraform plan -var-file=dev.tfvars -var='servers={}'terraforminfrastructure as codeplanpreview changes
A postcondition checks the result after a resource is created or read, using self, for example
"the AMI we found must be x86_64": condition = self.architecture == "x86_64". A top-level check
block runs assertions on every plan and apply but only warns, which suits health checks like "the
website returns 200".
The four look similar but fail differently, which matters in production:
| Check | Looks at | When it runs | If it fails |
|---|---|---|---|
validation in a variable | One input value | Before planning | Blocks the run |
precondition | Any assumption: several variables, data source results | Before planning or applying that resource | Blocks the run |
postcondition | The resource or data source's own result (self) | After it's read or applied | Blocks what depends on it |
check block | Anything, including live data | Every plan and apply | Warns only; the run continues |
So use validation for bad input, preconditions and postconditions for assumptions that must hold,
and check blocks for "tell me if this looks wrong" monitoring. A check is never a safety gate.
Add a prod environment safely
Using the servers project from this lesson, create prod.tfvars with env = prod, three replicas and a third server, db = t3.medium. Plan with it, then prove validation works by planning with env = production. Record the outputs a prod apply would create.
prod.tfvarsReveal one safe solution
$ printf 'env = "prod"\nreplicas = 3\nservers = { web = "t3.small", api = "t3.medium", db = "t3.medium" }\n' > prod.tfvars $ terraform plan -var-file=prod.tfvars | grep -E 'will be created|Plan:' $ terraform plan -var-file=prod.tfvars -var='env=production'
printf 'env = "prod"\nreplicas = 3\nservers = { web = "t3.small", api = "t3.medium", db = "t3.medium" }\n' > prod.tfvars>write output to a file, replacing it
terraform plan -var-file=prod.tfvars | grep -E 'will be created|Plan:'terraforminfrastructure as codeplanpreview changes|pipe: send output to the next commandgrepfind lines that match a pattern
The first plan should create 3 server files, 3 workers and the summary (7 to add). The second should
fail with "env must be dev, staging or prod." Note the order: the -var after -var-file wins.
Try it yourself
0 of 5 steps doneRun each task in your own account or terminal, then tick it off.
Quick check
TF_VAR_env=staging is set, terraform.tfvars has env = "dev", and you run plan -var="env=prod". Which value is used?
Official reading for this lesson
Or get every quiz answer right and it completes itself.
Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.