Bird
Raised Fist0
Terraformcloud~15 mins

Module inputs (variables) in Terraform - Deep Dive

Choose your learning style10 modes available
Overview - Module inputs (variables)
What is it?
Module inputs, also called variables, are named placeholders in Terraform modules that let you pass data from outside into the module. They allow you to customize how a module behaves without changing its code. Think of them as questions a module asks before it starts working, so it knows what to do.
Why it matters
Without module inputs, every time you want to reuse a module, you'd have to rewrite or copy it for each different use case. This would be slow, error-prone, and hard to maintain. Module inputs let you write a module once and use it many times with different settings, saving time and reducing mistakes.
Where it fits
Before learning module inputs, you should understand basic Terraform concepts like resources and modules. After mastering inputs, you can learn about outputs, module composition, and advanced features like variable validation and dynamic blocks.
Mental Model
Core Idea
Module inputs are like question forms that a module fills out before running, so it knows exactly what to build or configure.
Think of it like...
Imagine ordering a custom sandwich at a deli. The sandwich shop (module) asks you what bread, fillings, and toppings you want (inputs). Your choices tell the shop exactly how to make your sandwich without changing their recipe book.
┌───────────────┐
│   Module      │
│  ┌─────────┐  │
│  │ Inputs  │◄──── External values passed in
│  └─────────┘  │
│  ┌─────────┐  │
│  │ Logic   │  │
│  └─────────┘  │
│  ┌─────────┐  │
│  │ Outputs │  │
│  └─────────┘  │
└───────────────┘
Build-Up - 7 Steps
1
FoundationWhat are Terraform variables
🤔
Concept: Introduce variables as named placeholders for values that can change.
In Terraform, variables let you define a name and a type for a value you want to provide later. For example, you can create a variable called 'region' to specify where your cloud resources will be created. Variables are declared with 'variable' blocks and can have default values.
Result
You can write flexible Terraform code that doesn't hardcode values like regions or sizes.
Understanding variables is the first step to making your Terraform code reusable and adaptable.
2
FoundationDeclaring variables in modules
🤔
Concept: Show how to declare variables inside a Terraform module.
Inside a module folder, you create a file (usually variables.tf) where you declare variables using the syntax: variable "name" { type = string default = "value" } This tells Terraform that the module expects a value named 'name'.
Result
The module now expects inputs when used, making it configurable.
Declaring variables inside modules sets the contract for what inputs the module needs.
3
IntermediatePassing values to module inputs
🤔Before reading on: do you think module inputs can only be strings, or can they accept other types like lists or maps? Commit to your answer.
Concept: Explain how to provide values to module variables when calling a module, including different data types.
When you use a module in your Terraform configuration, you pass values to its variables like this: module "example" { source = "./module_path" name = "my-resource" tags = { env = "prod" } } Variables can be strings, numbers, booleans, lists, or maps. This flexibility lets you customize modules deeply.
Result
The module receives the values you provide and uses them to create resources accordingly.
Knowing that module inputs accept various types lets you design modules that handle complex configurations.
4
IntermediateVariable defaults and required inputs
🤔Before reading on: do you think all variables must be given a value when calling a module, or can some have defaults? Commit to your answer.
Concept: Teach how default values make variables optional and how missing required variables cause errors.
Variables can have default values, making them optional. For example: variable "region" { type = string default = "us-east-1" } If you don't pass a value for 'region', Terraform uses 'us-east-1'. If a variable has no default, Terraform requires you to provide a value or it will error.
Result
You can create modules that work with sensible defaults but still allow customization.
Understanding defaults helps you balance flexibility and simplicity in module design.
5
IntermediateVariable types and validation
🤔Before reading on: do you think Terraform variables accept any value without checks, or can you enforce rules on them? Commit to your answer.
Concept: Introduce variable type constraints and validation blocks to ensure inputs are correct.
Terraform lets you specify variable types like string, number, bool, list, map, or object. You can also add validation rules: variable "port" { type = number validation { condition = var.port > 0 && var.port < 65536 error_message = "Port must be between 1 and 65535" } } This prevents mistakes by catching bad inputs early.
Result
Modules become safer and more predictable by rejecting invalid inputs.
Knowing how to validate inputs prevents costly errors and improves module reliability.
6
AdvancedUsing complex types as inputs
🤔Before reading on: do you think module inputs can handle nested data like objects with multiple fields? Commit to your answer.
Concept: Explain how to use complex types like objects and maps of objects as module inputs for rich configurations.
You can define variables with complex types: variable "server" { type = object({ name = string cpu = number tags = map(string) }) } When calling the module, you pass a matching structure: server = { name = "web1" cpu = 4 tags = { env = "prod" } } This lets modules accept detailed, structured data.
Result
Modules can model real-world configurations more naturally and flexibly.
Mastering complex inputs unlocks powerful module designs that handle real infrastructure needs.
7
ExpertDynamic defaults and computed inputs
🤔Before reading on: do you think module inputs can have defaults that depend on other variables or computed values? Commit to your answer.
Concept: Show how to use expressions and functions to create dynamic default values and computed inputs inside modules.
Terraform allows default values to be expressions: variable "instance_type" { type = string default = var.environment == "prod" ? "m5.large" : "t3.micro" } You can also compute values inside modules using locals or conditional logic based on inputs. This makes modules smarter and adaptable without extra input from users.
Result
Modules can adjust behavior automatically, reducing the need for manual input.
Understanding dynamic inputs lets you build modules that simplify user experience and reduce errors.
Under the Hood
Terraform variables are processed during the plan phase. When you run Terraform, it reads variable declarations and merges values from defaults, environment variables, CLI flags, or module calls. Variables are stored in memory and used to fill resource arguments. Type constraints and validations run before applying changes to catch errors early.
Why designed this way?
Terraform was designed to separate configuration from code. Variables let users customize modules without changing code, promoting reuse and safety. Early versions had simple variables; later, types and validation were added to prevent misconfigurations and improve user experience.
┌───────────────┐
│ Variable Decl │
│ (type, def)   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Input Sources │
│ (CLI, Env,    │
│  Module call) │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│  Merge Values │
│  (defaults +  │
│   overrides)  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Validation &  │
│ Type Checking │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│  Resource     │
│  Configuration│
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think Terraform variables can be changed after apply without re-running Terraform? Commit to yes or no.
Common Belief:Variables are like environment variables and can be changed anytime without reapplying Terraform.
Tap to reveal reality
Reality:Terraform variables are inputs only during plan and apply. Changing a variable requires re-running Terraform to update resources.
Why it matters:Assuming variables can change live leads to confusion when infrastructure doesn't update as expected.
Quick: Do you think all variables must have default values? Commit to yes or no.
Common Belief:Every variable must have a default value or Terraform will fail.
Tap to reveal reality
Reality:Variables without defaults are required inputs and must be provided when running Terraform or calling modules.
Why it matters:Not providing required variables causes errors and blocks deployment.
Quick: Do you think variables can accept any data type without restrictions? Commit to yes or no.
Common Belief:Variables accept any value; type declarations are just suggestions.
Tap to reveal reality
Reality:Terraform enforces variable types strictly and rejects mismatched inputs.
Why it matters:Ignoring types leads to runtime errors and broken infrastructure.
Quick: Do you think module inputs can be changed inside the module after declaration? Commit to yes or no.
Common Belief:You can assign new values to variables inside the module code.
Tap to reveal reality
Reality:Variables are read-only inside modules; you cannot reassign them, only use them.
Why it matters:Trying to change variables inside modules causes errors and confusion.
Expert Zone
1
Variables with complex types can be combined with 'for_each' and 'dynamic' blocks to create highly flexible resource configurations.
2
Using variable validation not only prevents errors but also documents expected input formats, improving team collaboration.
3
Dynamic default values can introduce subtle bugs if they depend on other variables that might not be set yet, so order and dependencies matter.
When NOT to use
Avoid using variables for secrets or sensitive data; use dedicated secret management tools or Terraform's sensitive variable feature instead. Also, for very large or complex configurations, consider using data sources or external configuration management rather than overloading variables.
Production Patterns
In production, modules often define strict variable types and validations to enforce standards. Teams use variable files (.tfvars) per environment to manage inputs cleanly. Modules are versioned and inputs are carefully documented to ensure safe reuse across projects.
Connections
Function parameters (programming)
Module inputs in Terraform are like function parameters in programming languages.
Understanding function parameters helps grasp how inputs control behavior and reuse in Terraform modules.
Configuration management
Module inputs are a form of configuration management, separating code from data.
Knowing configuration management principles clarifies why inputs improve flexibility and reduce duplication.
User forms in web development
Module inputs resemble user input forms that customize application behavior.
Recognizing this connection shows how inputs collect necessary data before processing, a common pattern across fields.
Common Pitfalls
#1Forgetting to provide a required variable value when calling a module.
Wrong approach:module "example" { source = "./module_path" # missing required variable 'name' }
Correct approach:module "example" { source = "./module_path" name = "my-resource" }
Root cause:Not realizing variables without defaults must be explicitly set.
#2Passing a wrong data type to a variable.
Wrong approach:module "example" { source = "./module_path" count = "five" # should be a number, not string }
Correct approach:module "example" { source = "./module_path" count = 5 }
Root cause:Ignoring variable type constraints or misunderstanding expected types.
#3Trying to assign a new value to a variable inside the module.
Wrong approach:variable "name" { type = string } name = "new-name" # invalid assignment inside module
Correct approach:variable "name" { type = string } # Use var.name only, do not assign resource "aws_instance" "example" { name = var.name }
Root cause:Misunderstanding that variables are inputs, not mutable variables.
Key Takeaways
Module inputs (variables) let you customize Terraform modules without changing their code.
Variables can have types and default values, making them flexible and safe to use.
Passing the right values to module inputs controls how infrastructure is created or changed.
Validating variable inputs prevents errors and improves module reliability.
Understanding module inputs is essential for writing reusable, maintainable Terraform code.

Practice

(1/5)
1. What is the main purpose of using variables in a Terraform module?
easy
A. To customize module behavior without changing its code
B. To store sensitive data only
C. To define output values from the module
D. To create resources automatically

Solution

  1. Step 1: Understand module customization

    Variables allow users to provide input values to modules, changing how they behave without editing the module code itself.
  2. Step 2: Differentiate variables from other features

    Variables are not for outputs or automatic resource creation; they are inputs to customize modules.
  3. Final Answer:

    To customize module behavior without changing its code -> Option A
  4. Quick Check:

    Module inputs = customization [OK]
Hint: Variables customize modules without code edits [OK]
Common Mistakes:
  • Confusing variables with outputs
  • Thinking variables create resources
  • Assuming variables only store secrets
2. Which of the following is the correct syntax to declare a string variable named region with a default value of us-west-1?
easy
A. variable "region" = "us-west-1"
B. variable region { type = "string" default = us-west-1 }
C. variable "region" { default = us-west-1 type = string }
D. variable "region" { type = string default = "us-west-1" }

Solution

  1. Step 1: Check variable block syntax

    Terraform variables use the syntax: variable "name" { type = string default = "value" } with quotes around strings.
  2. Step 2: Validate variable "region" { type = string default = "us-west-1" }

    correctly uses quotes for the variable name and default string value, and sets type properly.
  3. Final Answer:

    variable "region" { type = string default = "us-west-1" } -> Option D
  4. Quick Check:

    Correct variable block syntax = variable "region" { type = string default = "us-west-1" } [OK]
Hint: Use quotes for names and string defaults in variable blocks [OK]
Common Mistakes:
  • Missing quotes around strings
  • Wrong order of attributes
  • Assigning variable directly without block
3. Given this module variable declaration:
variable "instance_count" {
  type    = number
  default = 2
}

And this usage inside the module:
resource "aws_instance" "example" {
  count = var.instance_count
  ami           = "ami-123456"
  instance_type = "t2.micro"
}

What will happen if the module is called without specifying instance_count?
medium
A. Only one instance will be created
B. Two AWS instances will be created
C. An error occurs because instance_count is missing
D. No instances will be created

Solution

  1. Step 1: Understand default variable behavior

    If a variable has a default value and is not overridden, Terraform uses the default.
  2. Step 2: Apply default to resource count

    The count argument uses var.instance_count, which defaults to 2, so two instances are created.
  3. Final Answer:

    Two AWS instances will be created -> Option B
  4. Quick Check:

    Default variable value used = 2 instances [OK]
Hint: Default variable values apply if no input given [OK]
Common Mistakes:
  • Assuming missing variable causes error
  • Thinking default is ignored
  • Confusing count with instance_type
4. You have this variable declaration inside a module:
variable "env" {
  type = string
}

When calling the module, you forget to provide a value for env. What will happen?
medium
A. Terraform will throw an error about missing required variable
B. Terraform will use an empty string as default
C. Terraform will assign null automatically
D. Terraform will use the string "env" as default

Solution

  1. Step 1: Check variable declaration for default

    The variable env has no default value, so it is required.
  2. Step 2: Understand Terraform behavior on missing required variables

    If a required variable is not provided, Terraform throws an error and stops.
  3. Final Answer:

    Terraform will throw an error about missing required variable -> Option A
  4. Quick Check:

    Required variable missing = error [OK]
Hint: No default means variable is required [OK]
Common Mistakes:
  • Assuming empty string or null is automatic default
  • Thinking Terraform guesses a value
  • Confusing variable name with default
5. You want to create a reusable module that accepts a list of subnet IDs as input. Which variable declaration correctly enforces that the input must be a list of strings and has no default value?
hard
A. variable "subnet_ids" { type = string default = [] }
B. variable "subnet_ids" { type = list number default = ["subnet-123"] }
C. variable "subnet_ids" { type = list(string) }
D. variable "subnet_ids" { type = list(string) default = null }

Solution

  1. Step 1: Identify correct type syntax for list of strings

    Terraform uses list(string) to specify a list where each item is a string.
  2. Step 2: Check default value presence

    No default means the variable is required. variable "subnet_ids" { type = list(string) } has no default, so input must be provided.
  3. Final Answer:

    variable "subnet_ids" { type = list(string) } -> Option C
  4. Quick Check:

    List of strings required, no default = variable "subnet_ids" { type = list(string) } [OK]
Hint: Use type = list(string) and omit default to require input [OK]
Common Mistakes:
  • Using wrong type like string instead of list(string)
  • Providing default empty list when input should be required
  • Using invalid syntax for type or default
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard