Terraform · Infrastructure as code
How do input variables work in Terraform?
Short answer
Input variables parameterise a configuration. Declare a type, description and optional default, validate bad values early, and pass values through tfvars, environment variables or CLI flags.
A variable block defines an input for a root module or child module. The type constrains what callers can pass, the default makes the input optional, and validation rejects values that break assumptions before a plan reaches the provider.
variable "environment" {
type = string
description = "Deployment environment"
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Environment must be dev, staging or prod."
}
}How values are supplied
- Defaults in the variable block
- terraform.tfvars and terraform.tfvars.json
- Files ending in .auto.tfvars, loaded in lexical order
- TF_VAR_name environment variables
- -var and -var-file flags, which take precedence over files
Avoid giving production-critical values a default in reusable modules. A missing input should fail loudly rather than quietly deploy to a default region or size. Mark secrets sensitive so they are redacted from plan output, while remembering that sensitivity does not encrypt state.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the precedence order for variable values?
- 2When should a variable have no default?
- 3Does marking a variable sensitive keep it out of state?
- 4How do you validate a variable's format?
Say it in the interview
Input variables are the parameters of a module. I give each one a type and description, add a default only when a safe default exists, and use validation for values like environment names. Values can come from tfvars files, TF_VAR variables or command-line flags, with flags taking precedence. Sensitive variables are redacted in output but still stored in state.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Terraform mock interview and get scored feedback on depth, clarity and confidence.