0
0
Terraformcloud~15 mins

Module inputs (variables) in Terraform - Deep Dive

Choose your learning style9 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.