Input Variables, Types & Validation
Variables are a configuration's parameters: the same code builds dev and prod with different values. A variable block declares one, with a type, an optional default, a description and any number of validation rules:
variable "environment" {
type = string
description = "Deployment environment: dev, staging or prod."
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "environment must be dev, staging or prod."
}
}A variable without a default is required. Interactive runs prompt for it; pipelines run with -input=false and fail instead, which is what you want.
Types
| Type | Example value |
|---|---|
string, number, bool |
"t3.micro", 3, true |
list(string) |
["eu-west-1a", "eu-west-1b"] |
set(string) |
like a list, unordered and without duplicates |
map(number) |
{ dev = 1, prod = 3 } |
object({ name = string, size = optional(number, 20) }) |
a record with named, typed fields; optional gives defaults |
tuple([string, number]) |
fixed length, a type per position |
any |
anything (avoid it in modules: no checking) |
Values are converted when possible ("3" becomes 3 for a number), and rejected with a clear error when not.
Setting values
mkdir v && cd v
cat > variables.tf <<'HCL'
variable "environment" {
type = string
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "environment must be dev, staging or prod."
}
}
variable "instance_count" {
type = number
default = 1
}
variable "db" {
type = object({
engine = string
version = string
storage = optional(number, 20)
})
default = { engine = "postgres", version = "17" }
}
HCL
cat > outputs.tf <<'HCL'
output "summary" {
value = "${var.environment}: ${var.instance_count} x app, ${var.db.engine} ${var.db.version} with ${var.db.storage} GiB"
}
HCL
echo 'instance_count = 2' > terraform.tfvars
echo 'environment = "staging"' > staging.tfvars
tofu init >/dev/null
echo "--- missing required value, no prompt"
tofu plan -input=false >/dev/null; echo "exit=$?"
echo "--- terraform.tfvars + a -var-file"
tofu apply -auto-approve -var-file=staging.tfvars | tail -1
echo "--- environment variable, then -var wins over it"
TF_VAR_environment=prod tofu apply -auto-approve -var instance_count=3 | tail -1
echo "--- validation"
tofu plan -var environment=qa >/dev/null; echo "exit=$?"--- missing required value, no prompt
Error: No value for required variable
on variables.tf line 1:
1: variable "environment" {
The root module input variable "environment" is not set, and has no default
value. Use a -var or -var-file command line argument to provide a value for
this variable.
exit=1
--- terraform.tfvars + a -var-file
summary = "staging: 2 x app, postgres 17 with 20 GiB"
--- environment variable, then -var wins over it
summary = "prod: 3 x app, postgres 17 with 20 GiB"
--- validation
Error: Invalid value for variable
on variables.tf line 1:
1: variable "environment" {
├────────────────
│ var.environment is "qa"
environment must be dev, staging or prod.
This was checked by the validation rule at variables.tf:3,3-13.
exit=1
Where values come from, from lowest to highest precedence (later wins):
- the
defaultin thevariableblock; - environment variables
TF_VAR_<name>; terraform.tfvars, thenterraform.tfvars.json(loaded automatically);*.auto.tfvars/*.auto.tfvars.jsonfiles, in alphabetical order;-varand-var-fileon the command line, in the order given.
OpenTofu also loads .tofu-specific files, and both CLIs accept complex values on the command line in HCL syntax: -var 'zones=["a","b"]'.
Validation rules
A condition can use any function; can() turns "this expression errors" into false, and alltrue checks every element of a collection. In current versions of both CLIs a condition may also refer to other variables (var.max >= var.min):
variable "cidr" {
type = string
validation {
condition = can(cidrhost(var.cidr, 0))
error_message = "cidr must be a valid IPv4 CIDR block, e.g. 10.0.0.0/16."
}
}
variable "azs" {
type = list(string)
validation {
condition = length(var.azs) >= 2 && alltrue([for z in var.azs : can(regex("^[a-z]{2}-[a-z]+-[0-9][a-z]quot;, z))])
error_message = "Give at least two zone names such as eu-west-1a."
}
}Validation runs before anything is planned, so a typo fails in seconds instead of half-way through an apply. For checks about resources (after their values are known), use precondition/postcondition in a lifecycle block or a top-level check block.
Sensitive values
sensitive = true hides a value in plan and apply output, and anything computed from it is hidden too:
mkdir s && cd s
cat > main.tf <<'HCL'
variable "db_password" {
type = string
sensitive = true
}
resource "terraform_data" "conn" {
input = "postgres://app:${var.db_password}@db.internal:5432/app"
}
output "conn" {
value = terraform_data.conn.output
sensitive = true
}
HCL
tofu init >/dev/null
TF_VAR_db_password='s3cr3t-value' tofu apply -auto-approve | sed -n '/will be created/,/^Plan/p;/^Outputs/,$p'
echo "--- but in the state file:"
grep -o 'postgres://[^"]*' terraform.tfstate | sort -u # terraform_data.conn will be created
+ resource "terraform_data" "conn" {
+ id = (known after apply)
+ input = (sensitive value)
+ output = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
Outputs:
conn = <sensitive>
--- but in the state file:
postgres://app:s3cr3t-value@db.internal:5432/app
That last line is the important lesson: sensitive only affects display. The value is stored in plain text in state. Protect state (an encrypted, access-controlled backend; OpenTofu state encryption), and where possible don't pass secrets through Terraform at all: let AWS generate and store the database password (manage_master_user_password in RDS in Code) or use ephemeral values (ephemeral = true on variables and outputs, ephemeral resources and write-only arguments), which both CLIs now support and which are never written to state or plan files.
Test yourself
terraform.tfvars sets region = "eu-west-1" and you run tofu plan -var region=us-east-1. Which value is used?
- eu-west-1
- us-east-1
- Neither: it is an error to set it twice
- The variable's default
What does sensitive = true on a variable guarantee?
- The value is encrypted in state
- The value is not shown in plan and apply output
- The value is never sent to the provider
- The value is stored in a vault
Why run pipelines with -input=false?
- It speeds up the plan
- A missing required variable fails the job instead of waiting forever for a prompt
- It disables validation
- It hides sensitive values