Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท Variables, Outputs and Data Sources

Input Variables and tfvars Files

Parameterize Terraform with input variables: type, default, description, nullable, passing values with -var, tfvars files and TF_VAR environment variables, and the precedence order.

A configuration with every value hard-coded works for exactly one environment. Input variables turn a configuration into a reusable template: the same code builds dev, staging and prod, each with its own region, size and name. Think of the root module as a function, and its variables as the function's parameters. Everything in this chapter follows from that picture.

HCL is read-only here; the stand-ins evaluate defaults, types and value precedence the way Terraform does.

Declaring a variable

HCL
variable "environment" {
  type        = string
  description = "Deployment environment: dev, staging or prod."
  default     = "dev"
}

Settings of a variable block (all optional):

Setting Purpose
type The type constraint; Terraform converts or rejects values
default Value used when none is supplied; makes the variable optional
description Documentation shown in prompts and generated docs; always write one
validation Custom rules (next lesson)
sensitive Hides the value in plan output (next lesson)
nullable Whether null is allowed (default true)
ephemeral Value is not stored in state or plan (Terraform 1.10+)

A variable without a default is required. Using it in an expression looks like var.environment. Variables are defined per module, and can be seen only inside it; to share a value between modules you pass it explicitly.

HCL
resource "aws_instance" "web" {
  instance_type = var.environment == "prod" ? "m6i.large" : "t3.micro"
}

Common types in practice

HCL
variable "region" {
  type = string
}

variable "replicas" {
  type    = number
  default = 2
}

variable "public" {
  type    = bool
  default = false
}

variable "zones" {
  type    = list(string)
  default = ["a", "b"]
}

variable "tags" {
  type    = map(string)
  default = {}
}

variable "database" {
  type = object({
    engine   = string
    size_gb  = number
    multi_az = optional(bool, false)
  })
}

If you omit type, Terraform accepts any, which hides mistakes. Always give a type; an object type makes the shape of your input self-documenting and lets Terraform catch a misspelled attribute before it reaches the provider.

Passing values

There are several ways to supply values. In increasing order of precedence:

  1. Defaults in the variable block.
  2. Environment variables named TF_VAR_<name>: export TF_VAR_region=eu-west-1. Handy in CI, and good for secrets.
  3. terraform.tfvars and terraform.tfvars.json, loaded automatically.
  4. *.auto.tfvars and *.auto.tfvars.json files, loaded automatically in alphabetical order.
  5. -var and -var-file command-line options, in the order given (last wins).

(Terraform Cloud/HCP and other platforms add workspace variables, with their own rules.) If a required variable still has no value, Terraform prompts for it interactively, or fails in non-interactive mode with "No value for required variable."

A .tfvars file is just assignments, no blocks:

HCL
# prod.tfvars
region      = "eu-central-1"
environment = "prod"
replicas    = 6
zones       = ["a", "b", "c"]
tags = {
  Team = "platform"
}

Use it with terraform apply -var-file=prod.tfvars. A common layout is one file per environment (dev.tfvars, prod.tfvars) or a folder per environment that each contains a terraform.tfvars. Never commit tfvars files with secrets; keep secrets in the environment, a secrets manager, or ignored files.

Terminal
export TF_VAR_db_password="from-ci-secret"
terraform apply -var-file=prod.tfvars -var="replicas=8"

Here replicas is 8: the -var option beats the file, which beats the default.

Python Variable value precedence (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

How type conversion applies to inputs

Values from -var and environment variables arrive as strings. Terraform converts them to the declared type: for number it parses "6", for bool it accepts true/false, and for list, map or object it parses HCL syntax in the string (-var='zones=["a","b"]'). In .tfvars files you write real HCL values. A failed conversion produces an error naming the variable, which is exactly why types are valuable.

Python Converting inputs to the declared type (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

nullable and optional object attributes

By default a caller may pass null for any variable. If you set nullable = false, null is replaced by the default value instead, which keeps defaults reliable inside modules:

HCL
variable "instance_type" {
  type     = string
  default  = "t3.micro"
  nullable = false
}

For objects, optional(type, default) marks single attributes as optional, as in multi_az = optional(bool, false) above.

Ephemeral and sensitive inputs

Variables that hold passwords or tokens should be marked sensitive = true. In Terraform 1.10 and later, ephemeral = true goes further: the value exists only during the run and is never written to state or plan files. That is the safer pattern for credentials that you pass to providers or write-only resource arguments. See the next lesson.

Variables in practice

  • Group related settings in one object variable instead of ten scalar ones.
  • Give each variable a description and a precise type.
  • Avoid defaults for values that should be an explicit decision (region, environment name, CIDR range). A required variable forces a conscious choice.
  • Keep per-environment values in files like prod.tfvars, committed to Git when they contain no secrets, so that environments are reviewable.
  • Do not read the same value from many places: define a variable once, pass it down through module inputs.

Where variable values come from

default Lowest priority.
TF_VAR_name Environment variables.
tfvars files terraform.tfvars, then *.auto.tfvars.
-var / -var-file Highest priority.

Later source wins.

1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A variable has no default. What happens if you run terraform apply without giving it a value in non-interactive mode?

    Variables without a default are required. Interactive runs prompt, non-interactive runs fail.
  2. 2. The default is 2, terraform.tfvars sets 4, and you run terraform apply -var="replicas=8". Which value wins?

    Command-line -var has the highest precedence, above tfvars files, environment variables and defaults.
  3. 3. How do you set the variable region from the shell for a single run, without a file?

    Environment variables must be named TF_VAR_ followed by the variable name.
  4. 4. What does nullable = false do for a variable with a default?

    With nullable = false, passing null falls back to the default instead of being used as null.

Summary

  • Variables parameterize a module; var.name reads them.
  • Use type, description and sensible defaults; no default means required.
  • Value sources by precedence: default, TF_VAR_*, terraform.tfvars, *.auto.tfvars, -var-file and -var.
  • Inputs arriving as strings are converted to the declared type; failures name the variable.
  • nullable = false and optional() make inputs more predictable.
  • Keep secrets out of committed tfvars; use sensitive and ephemeral.

Next: Variable Validation and Sensitive Values