Andrew Mercer
on this page

Think of a module as a function. Variables are its parameters, outputs are its return values, and locals are its private intermediate values. Most of what makes a module pleasant or painful to use lives on this page.

Input variables

variable "environment" {
  description = "Deployment environment. Drives naming and tagging only, never behaviour."
  type        = string
  nullable    = false

  validation {
    condition     = contains(["dev", "test", "prod"], var.environment)
    error_message = "environment must be one of: dev, test, prod."
  }
}

variable "admin_password" {
  description = "Initial admin password. Never stored in state when used with a write-only argument."
  type        = string
  sensitive   = true
  ephemeral   = true
}

Arguments

Argument Purpose
description Always set it. terraform-docs turns it into your README
type Type constraint (types). Always set it
default Makes the variable optional. No default = required
validation One or more condition / error_message blocks
sensitive Redacts the value in CLI output. Does not keep it out of state
ephemeral Value may only flow to ephemeral contexts and is never persisted to state or plan files (Terraform 1.10+, OpenTofu 1.11+)
nullable false means passing null uses the default instead of null (Terraform 1.1+). Set it on anything you don't want callers to null out
deprecated A message shown as a warning when the caller sets the variable (Terraform 1.15+; OpenTofu has had module variable deprecation since 1.11)

Validation

Validation runs at plan time against the variable's value. Since Terraform 1.9 (OpenTofu 1.8) a condition may reference other variables, locals and data sources, not just itself:

variable "min_replicas" { type = number }

variable "max_replicas" {
  type = number
  validation {
    condition     = var.max_replicas >= var.min_replicas
    error_message = "max_replicas (${var.max_replicas}) must be >= min_replicas (${var.min_replicas})."
  }
}

Validation patterns worth keeping:

# Regex shape check, safe against non-matching input
condition = can(regex("^[a-z0-9-]{3,24}$", var.name))

# Every element of a list
condition = alltrue([for cidr in var.address_space : can(cidrhost(cidr, 0))])

# Every value in a map of objects
condition = alltrue([for k, s in var.subnets : can(cidrnetmask(s.address_prefix))])

# Length limits (Azure storage account names!)
condition = length(var.storage_account_name) >= 3 && length(var.storage_account_name) <= 24

# Optional value: only validate when set
condition = var.retention_days == null || try(var.retention_days >= 7, false)

Validation fails closed: if the condition itself errors, the plan fails. Wrap anything that might error in can() or try().

Variable validation checks inputs. To check results (the subnet actually landed in the right range, the image is from the approved gallery), use preconditions and postconditions. To keep checking over time without blocking, use check blocks.

Sensitive values

sensitive = true hides the value in plan/apply output and marks anything derived from it as sensitive too. It's display hygiene, not security:

  • The value is still written to state in plaintext (if a resource stores it).
  • terraform output -json and terraform output -raw name reveal it.
  • nonsensitive() can strip the mark; use it only on values derived from a secret that are themselves safe (a hash, a length).

For values that must never touch state, see ephemeral values and write-only arguments and the security page.

Assigning values and precedence

From lowest to highest precedence; the last source wins:

  1. default in the variable block
  2. Environment variables TF_VAR_<name> (e.g. TF_VAR_environment=dev)
  3. terraform.tfvars
  4. terraform.tfvars.json
  5. *.auto.tfvars / *.auto.tfvars.json, in lexical filename order
  6. -var and -var-file on the command line, in the order given

Practical notes:

  • Complex types via environment variable use HCL syntax: TF_VAR_tags='{ env = "dev" }'.
  • Terragrunt passes inputs as TF_VAR_*, so they're the lowest-priority non-default source. An *.auto.tfvars in the module silently overrides them.
  • Variables that are set but not declared produce a warning for files and an error for -var. Keep terraform.tfvars clean.
  • In CI, prefer explicit -var-file=env/prod.tfvars over *.auto.tfvars, so the plan command line documents exactly what was loaded. See multi-environment configuration.

Output values

output "subnet_ids" {
  description = "Map of subnet name to subnet resource ID."
  value       = { for name, s in azurerm_subnet.this : name => s.id }
}

output "connection_string" {
  description = "Primary connection string. Sensitive."
  value       = azurerm_storage_account.this.primary_connection_string
  sensitive   = true
}
Argument Purpose
value Required. Any expression
description Document it
sensitive Required (Terraform errors otherwise) if the value contains anything sensitive
ephemeral Child modules only. Lets an ephemeral value pass up to the caller
type Explicit type constraint on the output (Terraform 1.15+)
deprecated Warning when callers reference the output (Terraform 1.15+)
depends_on Rarely needed. See dependencies
precondition Assert something about the value before exporting it

Output design guidance:

  • Outputs are your module's public API. Renaming one breaks every caller and every Terragrunt dependency or terraform_remote_state consumer. Treat a rename as a breaking change and use deprecated to give callers a release to migrate.
  • Return maps keyed by meaningful names, not lists. module.net.subnet_ids["aks"] survives reordering; module.net.subnet_ids[2] doesn't. The for expression above is explained in loops.
  • Return whole objects sparingly. value = azurerm_key_vault.this is convenient but couples callers to the provider schema and drags sensitive attributes along. Return the handful of attributes callers need.
  • Root module outputs are what terraform output shows and what other stacks read through remote state. Keep them small and stable.

Local values

locals {
  name_prefix = "${var.workload}-${var.environment}-${var.location_short}"

  tags = merge(var.tags, {
    environment = var.environment
    managed_by  = "terraform"
    repo        = "infrastructure.logging"
  })

  # Normalise a list input into the map shape for_each wants
  subnets_by_name = { for s in var.subnet_list : s.name => s }
}

Use locals to:

  • Name a computed value once so it isn't repeated (local.name_prefix).
  • Normalise input into the shape the resources need (list → map, defaults merged).
  • Give intent to a complex expression: local.is_zone_redundant reads better than a three-clause condition inline.

Don't use locals to:

  • Hide constants that should be inputs. If dev and prod need different values, it's a variable.
  • Build long chains where local.a feeds local.b feeds local.c across files. It turns the configuration into a puzzle. Keep locals close to where they're used, or in one locals.tf with comments.

Locals can reference variables, resources, data sources, modules and other locals, but not themselves (no recursion) and not in a cycle.

Variables vs locals vs data sources

Need Use
Value differs per caller or per environment Variable
Value computed from other values in the module Local
Value describes something that already exists in the cloud Data source
Value comes from another Terraform stack Data source by naming convention, or remote state (state)
Secret Ephemeral resource or data source from Key Vault/Vault, never a literal (security)