gotchabashterraformModerate
HCL basics: implicit type coercion causes silent mismatches in Terraform variables
Viewed 0 times
hcltype constraintvariable typecoercionterraform validateimplicit conversion
Problem
Terraform silently coerces values between types in HCL, so passing a number where a string is expected (or vice versa) does not always raise an error. This masks bugs where a variable receives the wrong type and the plan appears valid but produces incorrect infrastructure.
Solution
Always declare explicit types for all variables. Use type constraints like
string, number, bool, list(string), map(string), and object({...}). Enable terraform validate in CI to catch type mismatches before apply.variable "instance_count" {
type = number
description = "Number of EC2 instances to create"
default = 1
}
variable "tags" {
type = map(string)
default = {
Environment = "dev"
}
}Why
HCL performs automatic type coercion to be user-friendly, but this makes it easy to pass a stringified number or a boolean as a string without noticing until runtime behaviour differs from intent.
Gotchas
- The string
"true"and the booleantruebehave differently in conditionals — always use unquoted booleans - list() and tuple() are distinct types; mismatching them can cause unexpected diffs
- object() type constraints require exact attribute names — use map(string) for dynamic keys
- Omitting a type declaration defaults to
any, which accepts anything silently
Code Snippets
Explicit type declarations for common variable patterns
variable "enable_monitoring" {
type = bool
description = "Enable CloudWatch detailed monitoring"
default = false
}
variable "allowed_cidrs" {
type = list(string)
description = "CIDR blocks allowed inbound access"
default = ["10.0.0.0/8"]
}Context
Writing reusable Terraform modules or passing variables across modules
Revisions (0)
No revisions yet.