How to Pass Variables to Modules in Terraform
In Terraform, you pass variables to a module by defining
variable blocks inside the module and then providing values in the module block using arguments with the same names. This connects your main configuration to the module inputs cleanly and allows reuse.Syntax
To pass variables to a Terraform module, first declare variable blocks inside the module. Then, in the root configuration, use a module block and assign values to those variables by naming them as arguments.
- variable block: Defines input variables inside the module.
- module block: Calls the module and passes values to its variables.
terraform
module "example" { source = "./modules/example_module" variable_name = "value" another_variable = 123 } // Inside modules/example_module/variables.tf variable "variable_name" { type = string } variable "another_variable" { type = number }
Example
This example shows a root Terraform configuration passing variables to a module that creates an AWS S3 bucket. The module expects a bucket_name variable.
terraform
// Root configuration: main.tf module "s3_bucket" { source = "./modules/s3_bucket" bucket_name = "my-unique-bucket-123" } // Module variables: modules/s3_bucket/variables.tf variable "bucket_name" { type = string } // Module resource: modules/s3_bucket/main.tf resource "aws_s3_bucket" "bucket" { bucket = var.bucket_name acl = "private" }
Output
Terraform will create an AWS S3 bucket named "my-unique-bucket-123" using the module with the passed variable.
Common Pitfalls
Common mistakes when passing variables to modules include:
- Not declaring the variable inside the module, causing errors.
- Using a different variable name in the module and the module call.
- Forgetting to provide a value for a required variable.
Always ensure variable names match and required variables have values.
terraform
// Wrong: variable not declared in module module "example" { source = "./modules/example_module" missing_var = "value" } // Right: declare variable in module // modules/example_module/variables.tf variable "missing_var" { type = string }
Quick Reference
| Concept | Description | Example |
|---|---|---|
| variable block | Defines input variables inside a module | variable "name" { type = string } |
| module block | Calls a module and passes variables | module "mod" { source = "./mod" name = "value" } |
| Matching names | Variable names must match in module and call | var.name and name argument |
| Required variables | Must provide values or set defaults | variable "name" { type = string } |
Key Takeaways
Declare variables inside the module using variable blocks.
Pass values to module variables by naming them as arguments in the module block.
Variable names must match exactly between module and root configuration.
Always provide values for required variables or set default values.
Check for typos and missing declarations to avoid errors.