Chapter 1 · Practice 4 of 4
Give every variable and output a type and a description
From Structure and style
Why it matters
Untyped variables accept anything, so a typo in a .tfvars file shows up as a confusing error deep in a resource, or not at all. The style guide says every variable needs a type and a description, and every output a description too.
Also from the style guide:
- Give optional variables a sensible
default; leave required ones without one. - Only make something a variable if it really changes between deployments. Too many variables make a module harder to use, not more flexible.
- Use
validationblocks for unusually strict requirements, with an error message that says how to fix the value. - Order arguments as
type,description,default,sensitive,validation.
To check, run terraform validate and look at your module's generated docs (for example with terraform-docs). Any input without a description is a question someone will ask you later.
Example
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."
}
}