variable block — a foundational building block for creating reusable, well‑documented, and robust infrastructure code. A clearly defined variable block becomes a contract: it documents intent, enforces rules, and improves reuse across teams and automation pipelines.
A minimal variable declaration looks like:
type, default, or other arguments, Terraform treats the variable as a required input. If a value is not supplied at runtime, Terraform will prompt for it and stop execution until a value is provided. This behavior prevents accidental deployments with missing configuration.
Key arguments supported by the variable block
default— A fallback value. When present, the variable becomes optional.type— Enforces an expected type (for examplestring,list(string),object({...})). Terraform performs type checking before planning or applying.description— Human‑readable documentation that appears in CLI prompts and module docs.validation— A nested block that allows arbitrary expressions to validate input values (naming standards, allowed values, lengths, etc.). Validation is evaluated during the planning phase.sensitive— When true, Terraform hides the value in CLI output and logs. Note that sensitive values may still be stored in the state file.nullable— Controls whethernullis an allowed value.ephemeral— Not a Terraform core attribute. For short‑lived or run‑only secrets, prefer passing values via the CLI (-var), environment variables, a secrets manager, or using Terraform Cloud/Enterprise run‑only variables or other secret management integrations to avoid persisting secrets in state.
Use
sensitive = true together with secure state backends (for example, encrypted remote state) when handling secrets. sensitive masks output but does not prevent values from being stored in state.
Example: enforce a naming convention and length
validation block enforces:
- The value must start with the prefix
rg-. - The value must not exceed 20 characters.
- Enforce non‑empty or minimum length for an
rgvariable:
- Restrict
regionto an allowlist usingcontains:
Note: Precedence can be subtle and may vary between Terraform versions and environments. In general, CLI
-var and -var-file override values from files and environment variables, and defaults in the variable block have the lowest precedence. Consult the Terraform documentation for exact rules for your version.
Summary
- Use
type,description, andvalidationto make variables self‑documenting and expressive. - Explicit validations in shared modules and automation catch invalid inputs early.
- Protect secrets with
sensitive = trueand secure state backends;sensitiveonly masks output. - Choose an appropriate method to supply values (defaults,
tfvars, CLI, environment) and be aware of precedence for deterministic behavior.