DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

TerraformLesson 6 of 17
Your progress · 0%
On this page
  1. Input variables
  2. tfvars files
  3. Locals
  4. Outputs
  5. Preconditions and postconditions
↖ Course roadmap
Lesson 6 · Variables & outputs

Variables, locals and outputs

Make configurations reusable with typed variables and validation, .tfvars files, locals and outputs, and catch bad assumptions with preconditions.

30 min read · intermediate · hands-on

By the end of this lesson you'll be able to

0 of 5 complete
Lab status

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

Variables in, locals inside, outputs out. The bottom source on the left wins.© Diagram: DevOps Academy

Variables in, locals inside, outputs out. The bottom source on the left wins.© Diagram: DevOps Academy

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:

  • type makes Terraform reject the wrong shape early: a string where a number belongs, a list where a map belongs.
  • default makes the variable optional. env has none, so it's required and Terraform asks for it (or fails in CI).
  • description shows up in docs and prompts. Write it for the next person.
  • validation checks 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) and nullable = 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 code
  • planpreview 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.tfvars
  • terraforminfrastructure as code
  • planpreview 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:

  1. The default in the variable block
  2. Environment variables named TF_VAR_<name>, such as TF_VAR_env=dev
  3. terraform.tfvars, then terraform.tfvars.json
  4. *.auto.tfvars files, in alphabetical order
  5. -var and -var-file on 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 output
  • terraforminfrastructure 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 code
  • planpreview 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:

CheckLooks atWhen it runsIf it fails
validation in a variableOne input valueBefore planningBlocks the run
preconditionAny assumption: several variables, data source resultsBefore planning or applying that resourceBlocks the run
postconditionThe resource or data source's own result (self)After it's read or appliedBlocks what depends on it
check blockAnything, including live dataEvery plan and applyWarns 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.

⌘
Mini mission

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.

Input: variables.tf, main.tf and outputs.tf from this lessonOutput: prod.tfvars
Reveal 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 code
  • planpreview changes
  • |pipe: send output to the next command
  • grepfind 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 done

Run each task in your own account or terminal, then tick it off.

Knowledge check

Quick check

Question 1 of 4

TF_VAR_env=staging is set, terraform.tfvars has env = "dev", and you run plan -var="env=prod". Which value is used?

Go deeper

Official reading for this lesson

  • DocsInput variablesHashiCorp ↗
  • DocsVariable definition precedenceHashiCorp ↗
  • DocsLocal valuesHashiCorp ↗
  • DocsOutput valuesHashiCorp ↗
  • DocsCustom conditions (validation, preconditions, checks)HashiCorp ↗

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.

← PreviousResources: count, for_each and lifecycleNext lesson →fmt, validate and TFLint