🎓 A1Learner
🔍
0 of 50 lessons completed

Module Inputs, Outputs and Versions

A module keeps a contract with its callers. The inputs are what the caller must supply, the outputs are what the module gives back, and the version is the release the caller pins.

Required and optional inputs

name has no default, so the caller must pass it. shout has a default, so it is optional.

variable "name" {
  type        = string
  description = "The name written into the greeting."
}

variable "shout" {
  type    = bool
  default = false
}

Outputs hand values back

The caller reads this through module.greeting.message. A description says what the value means.

output "message" {
  value       = local_file.greeting.content
  description = "The greeting written to the file."
}

The version is part of the contract

For a Registry module, the version pins the release. The caller upgrades it only on purpose.

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.19.0"
}

Example

# modules/greeting/main.tf
variable "name" {
  type = string
}

variable "shout" {
  type    = bool
  default = false
}

resource "local_file" "greeting" {
  content  = var.shout ? upper("Hello from ${var.name}.") : "Hello from ${var.name}."
  filename = "${path.module}/${var.name}.txt"
}

output "message" {
  value = local_file.greeting.content
}

# main.tf
module "loud" {
  source = "./modules/greeting"
  name   = "loud"
  shout  = true
}

module "quiet" {
  source = "./modules/greeting"
  name   = "quiet"
}

output "loud_message" {
  value = module.loud.message
}

output "quiet_message" {
  value = module.quiet.message
}

Key points

  • Inputs are variables declared inside the module.
  • A required input has no default, so the caller must supply it.
  • An optional input has a default, so the caller may leave it out.
  • Outputs are the values the module hands back to the caller.
  • A good module outputs the values the caller needs next.
  • The version pins the module to one release for Registry modules.

The module takes a name and an optional shout flag. The loud call passes true and gets capital letters; the quiet call leaves the default and gets normal text. Both outputs show the contract at work.

Note

Changing an input name or an output name breaks every caller, so treat them as a promise.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What is the contract a module keeps?