What Is a Module?
A module is a folder of .tf files that does one job. It takes inputs, builds resources, and gives back outputs, so the same folder can be used again and again.
A module is a folder
The folder holds the resources, the variables, and the outputs for one job.
modules/
greeting/
main.tf
variables.tf
outputs.tfCall the module
The source points at the folder. The inputs follow, just like arguments to a function.
module "greeting" {
source = "./modules/greeting"
name = "hello"
}Read the module output
Outputs are read through the module name. The root can use them in its own outputs.
output "message" {
value = module.greeting.message
}Example
# modules/greeting/main.tf
variable "name" {
type = string
}
resource "local_file" "greeting" {
content = "Hello from ${var.name}."
filename = "${path.module}/${var.name}.txt"
}
output "message" {
value = local_file.greeting.content
}
# main.tf
module "first" {
source = "./modules/greeting"
name = "first"
}
module "second" {
source = "./modules/greeting"
name = "second"
}
output "first_message" {
value = module.first.message
}Key points
- A module is a folder, not a single file.
- Its inputs are variables declared inside the folder.
- Its outputs are values declared inside the folder.
- The root configuration is itself a module, called the root module.
- A module is called with a module block and a source path.
- The same module can be called more than once with different inputs.
The module is one folder with its own inputs and outputs. The root calls it twice with different names, and each call builds its own file.
Note
Copying and pasting a block is not reuse. A module is reuse.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What is a module in Terraform?