TExcelTAD
Home › Infrastructure as Code: Terraform & OpenTofu › Modules: Calling & Writing

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.

hcl
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

bash · try it yourself
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.replicas
Initializing 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
  • init registers local modules (- api in modules/service) and installs the providers the modules use. This module doesn't declare required_providers, so init took the latest hashicorp/local it could find ("Finding latest version"): real modules should declare it, as the next lesson shows. Remote modules are downloaded into .terraform/modules. Run init again whenever you add a module block or change a source.
  • Resources inside a module get addresses prefixed by the call: module.api.local_file.unit. Use those addresses in state show, -target, moved and import.
  • Paths: path.module is the module's own folder (for its templates and files), path.root the root module's folder, path.cwd the 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:

bash · try it yourself
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 list
Outputs:

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:

hcl
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"?

  1. network.vpc_id
  2. module.network.vpc_id, where vpc_id is an output of the module
  3. module.network.aws_vpc.this.id
  4. var.network.vpc_id

What is the state address of local_file.unit inside module "api"?

  1. local_file.unit
  2. api.local_file.unit
  3. module.api.local_file.unit
  4. modules/service/local_file.unit

Should a reusable module contain provider "aws" { region = "eu-west-1" }?

  1. Yes, always
  2. No: declare required_providers, let the caller configure providers and pass aliases via providers = {}
  3. Only for the default region
  4. Only in OpenTofu