Input Variable
A Terraform input variable is a parameter that lets callers pass different values into a configuration or module. It is declared with a variable block and can define a type, default, description, validation, and sensitivity.
What Is an Input Variable?
You declare a value once and reference it as var.name, so changing a region or size means editing one place.
HCL
variable "environment" { description = "Deployment environment" type = string default = "dev" validation { condition = contains(["dev", "staging", "prod"], var.environment) error_message = "Must be dev, staging, or prod." }}A variable with no default is required.
Precedence (later wins)
- Defaults, then
TF_VAR_nameenvironment variables terraform.tfvars, then*.auto.tfvarsin alphabetical order-varand-var-fileflags, in command-line order
Security
sensitive = truehides a value from CLI output only. It is still stored in plaintext in state.
Frequently Asked Questions
Why add type and validation to a variable?
Terraform rejects bad input at plan time with a clear message, instead of failing later inside a resource with a confusing error.
Should every variable have a default?
No. A default on something environment-critical can silently ship to production. Omit it to force the caller to choose.
Found a mistake, an outdated step or a broken link?