Modules: Calling & Writing
A module is a folder of .tf files. You have been writing one all along: the folder you run the CLI in is the root module. Any other folder can be called from it with a module block, which passes input variables in and gets outputs back, like calling a function.
module "network" {
source = "./modules/network" # where the module's code is
name = "linkly-prod" # = its variable "name"
cidr = "10.20.0.0/16"
}
resource "aws_instance" "web" {
subnet_id = module.network.private_subnet_ids[0] # = its output "private_subnet_ids"
# …
}Modules are how you stop copy-pasting: the VPC layout, the "service with a queue and an IAM role" pattern, the database with its subnet group and parameters are written once and called per environment or per service.
A module, called twice
mkdir -p proj/modules/service && cd proj
cat > modules/service/variables.tf <<'HCL'
variable "name" {
type = string
description = "Service name, used in every file name."
}
variable "port" {
type = number
description = "Port the service listens on."
}
variable "replicas" {
type = number
default = 1
}
HCL
cat > modules/service/main.tf <<'HCL'
resource "local_file" "unit" {
filename = "${path.root}/out/${var.name}.service"
content = "[Service]\nExecStart=/usr/bin/${var.name} --port ${var.port}\n"
}
resource "local_file" "scale" {
filename = "${path.root}/out/${var.name}.replicas"
content = "${var.replicas}\n"
}
HCL
cat > modules/service/outputs.tf <<'HCL'
output "unit_file" {
value = local_file.unit.filename
}
HCL
cat > main.tf <<'HCL'
module "api" {
source = "./modules/service"
name = "api"
port = 8080
replicas = 3
}
module "worker" {
source = "./modules/service"
name = "worker"
port = 9090
}
output "units" {
value = [module.api.unit_file, module.worker.unit_file]
}
HCL
tofu init | grep -E '^- |Initializing modules'
tofu apply -auto-approve | sed -n '/^Apply/,$p'
tofu state list
cat out/worker.replicasInitializing modules...
- api in modules/service
- worker in modules/service
- Finding latest version of hashicorp/local...
- Installing hashicorp/local v2.9.1...
- Installed hashicorp/local v2.9.1 (unauthenticated)
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
Outputs:
units = [
"./out/api.service",
"./out/worker.service",
]
module.api.local_file.scale
module.api.local_file.unit
module.worker.local_file.scale
module.worker.local_file.unit
1
initregisters local modules (- api in modules/service) and installs the providers the modules use. This module doesn't declarerequired_providers, soinittook the latesthashicorp/localit could find ("Finding latest version"): real modules should declare it, as the next lesson shows. Remote modules are downloaded into.terraform/modules. Runinitagain whenever you add a module block or change asource.- Resources inside a module get addresses prefixed by the call:
module.api.local_file.unit. Use those addresses instate show,-target,movedandimport. - Paths:
path.moduleis the module's own folder (for its templates and files),path.rootthe root module's folder,path.cwdthe directory the CLI was started in. - The module's resources can't be referenced from outside, only its outputs. That boundary is the whole point: callers depend on the interface, not the internals.
Multiple instances: for_each on modules
count and for_each work on module blocks too. One map of settings, one module instance per entry:
mkdir -p proj/modules/service && cd proj
cat > modules/service/main.tf <<'HCL'
variable "name" {
type = string
}
variable "port" {
type = number
}
resource "local_file" "unit" {
filename = "${path.root}/out/${var.name}.service"
content = "ExecStart=/usr/bin/${var.name} --port ${var.port}\n"
}
output "unit_file" {
value = local_file.unit.filename
}
HCL
cat > main.tf <<'HCL'
locals {
services = {
api = 8080
worker = 9090
cron = 9100
}
}
module "svc" {
for_each = local.services
source = "./modules/service"
name = each.key
port = each.value
}
output "units" {
value = { for k, m in module.svc : k => m.unit_file }
}
HCL
tofu init >/dev/null
tofu apply -auto-approve | sed -n '/^Outputs:/,$p'
tofu state listOutputs:
units = {
"api" = "./out/api.service"
"cron" = "./out/cron.service"
"worker" = "./out/worker.service"
}
module.svc["api"].local_file.unit
module.svc["cron"].local_file.unit
module.svc["worker"].local_file.unit
Adding a service is one line in the map; removing worker destroys only module.svc["worker"], for the reasons explained in for_each & Stable Keys.
Providers and modules
A module inherits the default provider configurations of its caller: the aws provider configured in the root is used inside every module. A module should declare which providers it needs (required_providers) but never configure them (no provider blocks with region or credentials inside a reusable module). To give a module a non-default configuration, pass it explicitly:
module "dr_bucket" {
source = "./modules/bucket"
providers = {
aws = aws.us # the module's "aws" is the caller's aws.us
}
}Test yourself
How does the root module read a value from module "network"?
network.vpc_idmodule.network.vpc_id, wherevpc_idis an output of the modulemodule.network.aws_vpc.this.idvar.network.vpc_id
What is the state address of local_file.unit inside module "api"?
local_file.unitapi.local_file.unitmodule.api.local_file.unitmodules/service/local_file.unit
Should a reusable module contain provider "aws" { region = "eu-west-1" }?
- Yes, always
- No: declare required_providers, let the caller configure providers and pass aliases via
providers = {} - Only for the default region
- Only in OpenTofu