0
0
Terraformcloud~15 mins

Default values in Terraform - Deep Dive

Choose your learning style9 modes available
Overview - Default values
What is it?
Default values in Terraform are preset values assigned to variables or resource arguments when no other value is provided. They allow configurations to work smoothly without requiring users to specify every detail. This makes Terraform code more flexible and easier to reuse. Defaults act like fallback options that keep your infrastructure code running even if some inputs are missing.
Why it matters
Without default values, every user of a Terraform module or configuration would have to specify every variable manually, which is tedious and error-prone. Defaults save time and reduce mistakes by providing sensible starting points. They also make modules more user-friendly and adaptable to different environments. Without defaults, infrastructure automation would be less efficient and more fragile.
Where it fits
Before learning default values, you should understand Terraform variables and basic configuration syntax. After mastering defaults, you can explore advanced variable types, input validation, and module design. Default values fit early in the Terraform learning path as a foundation for flexible and maintainable infrastructure code.
Mental Model
Core Idea
Default values are backup answers Terraform uses when you don’t give it one.
Think of it like...
Imagine ordering a coffee at a cafe. If you don’t specify the size, the barista gives you the regular size by default. This default size ensures you get a coffee without needing to say every detail.
┌───────────────┐
│ Terraform Run │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Check Variable│
│   Value?      │
└──────┬────────┘
   Yes │ No
       ▼
┌───────────────┐
│ Use Provided  │
│    Value      │
└───────────────┘
       │
       ▼
┌───────────────┐
│ Use Default   │
│    Value      │
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Terraform Variables
🤔
Concept: Variables hold values that can change between Terraform runs.
Terraform variables let you write flexible code by replacing fixed values with placeholders. You declare variables in a file using the 'variable' block, giving them a name and optionally a type. For example: variable "region" { type = string } You can then provide values when running Terraform or in files.
Result
You can reuse the same Terraform code in different environments by changing variable values.
Understanding variables is essential because default values only apply to variables, making your code adaptable.
2
FoundationDeclaring Default Values for Variables
🤔
Concept: You can assign a default value to a variable so Terraform uses it if no other value is given.
Add a 'default' argument inside the variable block: variable "region" { type = string default = "us-west-1" } If you don’t provide a value for 'region', Terraform uses 'us-west-1'.
Result
Terraform runs without errors even if you don’t specify the 'region' variable.
Default values reduce the need to specify every variable, making your code easier to use and less error-prone.
3
IntermediateDefault Values with Complex Types
🤔Before reading on: do you think default values can only be simple strings or numbers? Commit to your answer.
Concept: Defaults can be complex types like lists, maps, or objects, not just simple values.
You can set defaults for lists: variable "availability_zones" { type = list(string) default = ["us-west-1a", "us-west-1b"] } Or maps: variable "tags" { type = map(string) default = { environment = "dev" team = "cloud" } } This lets you provide rich default configurations.
Result
Terraform uses the full list or map as the default when no value is provided.
Knowing defaults support complex types lets you build more powerful and flexible modules.
4
IntermediateOverriding Default Values
🤔Before reading on: if you provide a value for a variable with a default, which value does Terraform use? Commit to your answer.
Concept: User-provided values always override defaults when given.
If you run Terraform with a variable file or command-line input, those values replace the defaults: terraform apply -var='region=eu-central-1' Here, 'eu-central-1' is used instead of the default 'us-west-1'.
Result
Terraform uses the user’s value, ignoring the default.
Understanding override behavior helps avoid confusion about which values Terraform applies.
5
IntermediateDefault Values in Module Inputs
🤔
Concept: Modules can define variables with defaults, making them easier to reuse without always specifying inputs.
Inside a module, you declare variables with defaults: variable "instance_type" { type = string default = "t3.micro" } When calling the module, you can omit 'instance_type' and it uses the default.
Result
Modules become more user-friendly and flexible with sensible defaults.
Defaults in modules reduce boilerplate and make sharing infrastructure code simpler.
6
AdvancedCombining Defaults with Validation Rules
🤔Before reading on: do you think Terraform allows defaults that break validation rules? Commit to your answer.
Concept: Terraform lets you set validation rules that check variable values, including defaults.
You can add validation inside variables: variable "instance_count" { type = number default = 2 validation { condition = var.instance_count > 0 error_message = "Must be greater than zero." } } If the default breaks the rule, Terraform errors before running.
Result
Defaults must be valid or Terraform refuses to run.
Validation ensures defaults are safe and prevents subtle bugs from bad defaults.
7
ExpertDefault Values and Lazy Evaluation
🤔Before reading on: do you think default values are computed once or every time they are used? Commit to your answer.
Concept: Default values can use expressions that Terraform evaluates lazily at runtime, not just static values.
You can write defaults using expressions: variable "ami_id" { type = string default = data.aws_ami.ubuntu.id } Terraform evaluates 'data.aws_ami.ubuntu.id' only when needed. This allows dynamic defaults based on other resources or data sources.
Result
Defaults can adapt to changing environments without manual updates.
Lazy evaluation of defaults enables powerful, context-aware infrastructure automation.
Under the Hood
Terraform processes variables during the plan phase. When it encounters a variable, it first checks if a value was provided via CLI, environment, or files. If none is found, it uses the default value declared in the variable block. Defaults are stored in the state and used throughout the apply phase. Complex defaults are parsed and evaluated lazily if they contain expressions referencing other resources or data sources.
Why designed this way?
Defaults were designed to simplify user experience and reduce configuration errors. Early Terraform versions required all variables to be specified, which was cumbersome. Allowing defaults made modules reusable and lowered the barrier to entry. Lazy evaluation was introduced to support dynamic infrastructure where defaults depend on runtime data, balancing flexibility with predictability.
┌───────────────┐
│ Start Terraform│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Check Variable│
│  Input Value? │
└──────┬────────┘
   Yes │ No
       ▼
┌───────────────┐
│ Use Input     │
│   Value       │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Use Default   │
│   Value       │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Evaluate if   │
│ Expression?   │
└──────┬────────┘
   Yes │ No
       ▼
┌───────────────┐
│ Compute Value │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Continue Plan │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: If a variable has a default, do you still need to provide a value every time? Commit to yes or no.
Common Belief:If a variable has a default, you must always provide a value to override it.
Tap to reveal reality
Reality:You only provide a value if you want to override the default; otherwise, Terraform uses the default automatically.
Why it matters:Thinking you must always provide values leads to unnecessary work and confusion about how defaults work.
Quick: Can default values be expressions that depend on other resources? Commit to yes or no.
Common Belief:Defaults must be static values and cannot depend on other resources or data sources.
Tap to reveal reality
Reality:Defaults can be expressions evaluated lazily, allowing dynamic values based on other resources.
Why it matters:Believing defaults are static limits your ability to write flexible, dynamic infrastructure code.
Quick: Does Terraform ignore default values if a variable is marked as required? Commit to yes or no.
Common Belief:Marking a variable as required means defaults are ignored and values must be provided.
Tap to reveal reality
Reality:Terraform does not have a 'required' keyword; variables with defaults are optional, and those without must be provided.
Why it matters:Misunderstanding this causes confusion about variable requirements and leads to deployment errors.
Quick: If a default value breaks a validation rule, will Terraform accept it? Commit to yes or no.
Common Belief:Terraform will accept default values even if they break validation rules.
Tap to reveal reality
Reality:Terraform enforces validation on defaults and errors out if defaults are invalid.
Why it matters:Assuming invalid defaults are allowed can cause unexpected failures during deployment.
Expert Zone
1
Default values are evaluated lazily, so they can reference data sources or resources that are only available at plan time.
2
When multiple variable value sources exist (CLI, environment, tfvars files), Terraform uses a strict priority order, and defaults are the lowest priority fallback.
3
Defaults in modules enable backward compatibility when adding new variables, preventing breaking changes for existing users.
When NOT to use
Avoid using defaults when a variable must always be explicitly set for security or compliance reasons, such as passwords or sensitive keys. Instead, mark variables without defaults and use input validation. For complex conditional defaults, consider using locals or conditional expressions outside variables.
Production Patterns
In production, defaults are used to provide safe, common configurations while allowing overrides for environment-specific settings. Modules often include defaults for instance sizes, regions, or tags. Defaults combined with validation ensure infrastructure is consistent and reduces human error during deployments.
Connections
Function Default Parameters (Programming)
Both provide fallback values when no explicit input is given.
Understanding default values in programming functions helps grasp Terraform defaults as a way to simplify user input and avoid errors.
Configuration Management (DevOps)
Defaults in Terraform variables resemble default settings in configuration files for software deployment.
Knowing how defaults work in config management tools clarifies why Terraform uses defaults to make infrastructure code flexible and reusable.
Decision Trees (Mathematics)
Terraform’s choice between user input and default values follows a decision path similar to branches in decision trees.
Recognizing this decision process helps understand how Terraform selects values and why order of precedence matters.
Common Pitfalls
#1Assuming default values are always used regardless of input.
Wrong approach:variable "region" { type = string default = "us-east-1" } # User provides -var='region=us-west-2' # Expecting default 'us-east-1' to be used anyway.
Correct approach:variable "region" { type = string default = "us-east-1" } # User provides -var='region=us-west-2' # Terraform uses 'us-west-2' as expected.
Root cause:Misunderstanding that user inputs override defaults leads to confusion about which value Terraform applies.
#2Setting invalid default values that break validation rules.
Wrong approach:variable "instance_count" { type = number default = 0 validation { condition = var.instance_count > 0 error_message = "Must be greater than zero." } }
Correct approach:variable "instance_count" { type = number default = 1 validation { condition = var.instance_count > 0 error_message = "Must be greater than zero." } }
Root cause:Not aligning default values with validation rules causes Terraform to error unexpectedly.
#3Using defaults for sensitive variables like passwords.
Wrong approach:variable "db_password" { type = string default = "changeme" sensitive = true }
Correct approach:variable "db_password" { type = string sensitive = true # No default, must be provided }
Root cause:Providing defaults for sensitive data risks security and defeats the purpose of requiring secure inputs.
Key Takeaways
Default values in Terraform provide fallback inputs that make configurations easier to use and more flexible.
User-provided values always override defaults, so defaults only apply when no input is given.
Defaults can be simple or complex types and support expressions evaluated at runtime.
Validation rules apply to defaults, ensuring they are safe and valid before deployment.
Using defaults wisely improves module reusability and reduces errors but avoid defaults for sensitive or mandatory inputs.