A module input has many optional settings with defaults. How do you type it?
IntermediateScenarioResources Variables and Expressions
Answer
Situation read → A flat list of 20 variables is painful; an untyped map is dangerous.
What I'd do → Use an object with optional() attributes and defaults.
variable "database" {
type = object({
engine = string
instance_class = optional(string, "db.t4g.medium")
multi_az = optional(bool, false)
backup_days = optional(number, 7)
})
}
Why → Callers set only what differs, typos are rejected at plan, and defaults are visible in one place.
Interview tip → optional() with a default has been stable since Terraform 1.3.
More on Resources Variables and Expressions
You need three identical web servers. How do you declare them, and what is the catch with `count`?BeginnerYou manage subnets from a list of CIDRs. Someone removes the second CIDR and Terraform plans to recreate the third subnet. Why, and what do you change?IntermediateHow do you stop someone passing `environment = "production"` when only `dev`, `stage` and `prod` are valid?BeginnerA module takes a database password and exposes the connection string as an output. How do you stop them leaking into plan output?BeginnerA monitoring stack should only exist in prod. How do you create a resource conditionally?BeginnerYou have subnets defined as `{ web = {...}, db = {...} }` per VPC, nested two levels deep. How do you create them with `for_each`?Advanced