Module Input Variables
What you'll learn: How to define input variables inside Terraform modules to make them flexible and reusable across different environments.
Why Modules Need Variables
Think of a module as a template for infrastructure. Just like a form with blank fields, a module becomes truly useful when you can customize it without rewriting the entire thing. Input variables are those blank fields—they let you pass different values each time you use the module.
Defining Variables Inside a Module
Inside your module's directory, you declare input variables in a variables.tf file (or any .tf file). These work exactly like the root-level variables you've already learned:
# modules/web-server/variables.tf
variable "instance_type" {
type = string
description = "EC2 instance type for the web server"
default = "t2.micro"
}
variable "environment" {
type = string
description = "Environment name (dev, staging, prod)"
}
Passing Values When Calling the Module
When you call a module with a module block, you pass values to its input variables as arguments:
# Root module
module "production_web" {
source = "./modules/web-server"
instance_type = "t2.large"
environment = "prod"
}
The module receives these values and uses them internally in its resources. This means one module definition can create dev, staging, and production infrastructure—just by changing the input values.
Variables Make Modules Portable
Without input variables, modules would be hardcoded and inflexible. With them, you can share modules across teams, projects, and cloud accounts, simply adjusting the inputs to fit each use case.
Key Takeaway: Module input variables act as customizable parameters that make modules configurable and reusable—define them inside the module, then pass different values when calling the module for each environment or use case.