Default Values and Optional Variables
What You'll Learn
You'll learn how to make Terraform variables optional by setting default values, reducing configuration overhead and making your modules easier to use.
Why Default Values Matter
When you declare a variable in Terraform, you can provide a default value. If a default is set, that variable becomes optional—users can skip providing it entirely, and Terraform will automatically use your default. Without a default, the variable is required, and Terraform will prompt for it or error if it's missing.
Think of default values like pre-filled form fields: the user can change them if needed, but they don't have to stop and fill in every single blank.
Setting Default Values
Add a default argument to your variable block:
variable "instance_type" {
type = string
description = "EC2 instance type"
default = "t2.micro"
}
variable "enable_monitoring" {
type = bool
default = true
}
variable "tags" {
type = map(string)
default = {
Environment = "dev"
ManagedBy = "Terraform"
}
}
Now users of your configuration can omit these variables entirely, and Terraform will use "t2.micro", true, and the default tag map respectively.
When to Use Defaults
Use defaults for:
- Sensible, commonly-used values
- Non-sensitive configuration (never default secrets!)
- Making your modules beginner-friendly
Leave variables without defaults when:
- The value must be explicitly chosen (like region or project name)
- You want to force conscious decision-making
Key Takeaway: Setting default values makes variables optional, simplifying configuration for common use cases while still allowing customization when needed.