Skip to content

Structuring Terraform with modules and the dependency graph

The Terraform article on this site introduces modules, the dependency graph, and the lifecycle meta-argument in a sentence or two each, and Managing Terraform state in practice covers the state file itself. This article goes deeper on the three things that decide whether a growing Terraform codebase stays maintainable: how to package config as reusable modules, how Terraform derives the order it applies changes in, and how to control replacement so a routine change never drops traffic.

Modules: package a design once, call it many times

A module is just a directory of .tf files with declared inputs and outputs. Every Terraform configuration is already a module — the root module in your working directory — and you factor common patterns into child modules so you stop copy-pasting the same twenty lines per site.

HashiCorp's standard module structure is three files, any of which may be empty: main.tf for resources, variables.tf for inputs, and outputs.tf for values you expose to the caller. A "branch-site" module that stamps out the VLANs for one location looks like this:

# modules/branch_site/variables.tf
variable "site_id" {
  description = "Short site code, used to tag resource names"
  type        = string
}

variable "vlans" {
  description = "VLAN ID to name mapping for this site"
  type        = map(string)
}
# modules/branch_site/main.tf
resource "iosxe_vlan" "site" {
  for_each = var.vlans
  vlan_id  = tonumber(each.key)
  name     = "${upper(var.site_id)}-${each.value}"
}
# modules/branch_site/outputs.tf
output "vlan_ids" {
  description = "IDs of the VLANs created for this site"
  value       = [for v in iosxe_vlan.site : v.vlan_id]
}

The root module calls it once per site, passing different inputs each time:

module "branch_dublin" {
  source  = "./modules/branch_site"
  site_id = "dub"
  vlans   = { "10" = "SALES", "20" = "VOICE" }
}

Give every variable and output a one- or two-sentence description — it is the module's interface documentation, and terraform surfaces it in generated docs and error messages. Make an input required by omitting its default; a variable with a default is optional. And wire outputs to real resource attributes (iosxe_vlan.site[...].vlan_id) rather than passing an input straight back out, so the value stays inside the dependency graph described next.

The dependency graph: Terraform derives the order, you don't

Terraform is declarative, so you never write an order of operations — it computes one. During plan it builds a directed dependency graph from the references between resources. If one resource interpolates an attribute of another — the OSPF block referencing iosxe_vlan.site["10"].vlan_id, say — Terraform records that the VLAN must exist first. Everything with no reference between it runs in parallel. Two practical consequences fall out of this:

  • The order of blocks and files is irrelevant. Splitting intent across vlans.tf, interfaces.tf, and routing.tf is purely organizational; Terraform re-derives the graph every run.
  • A reference is the right way to express "A before B." Prefer an implicit dependency (B reads an attribute of A) over a manual one, because it also passes the real value along.

When an ordering exists on the device but not in any attribute reference, state it explicitly with depends_on. Reach for it sparingly — every depends_on you add by hand is an edge Terraform could not infer, and an over-broad one serializes work that could have run concurrently.

The lifecycle meta-argument: control how changes are applied

By default, when a change can't be done in place, Terraform destroys the old object before creating the replacement — an outage window for anything carrying traffic. The lifecycle block tunes that behavior:

resource "iosxe_interface_ethernet" "uplink" {
  type        = "GigabitEthernet"
  name        = "1/0/1"
  description = "core-uplink"

  lifecycle {
    create_before_destroy = true          # build the replacement first — no gap
    prevent_destroy       = true          # refuse any plan that would delete this uplink
    ignore_changes        = [description] # an external NMS owns this field
  }
}
  • create_before_destroy reverses the default order so the new object is built before the old one is torn down. Terraform propagates this to the resource's dependencies and will not let a dependency override it back to false.
  • prevent_destroy makes Terraform reject any plan that would destroy the object, terraform destroy included. Note the escape hatch: deleting the resource block from your config removes the guard along with it, so Terraform can then destroy the object on the next apply.
  • ignore_changes lists attributes Terraform should stop reconciling because another system manages them; ignore_changes = all ignores every attribute. It only applies to attributes the resource type actually defines.
  • replace_triggered_by (Terraform 1.2+) forces replacement when a referenced resource or attribute changes — useful when a device object must be rebuilt because something upstream of it was.

When a plan does force a replacement, read the symbols: -/+ means destroy then create (the default), while +/- means create then destroy — the safer order you get from create_before_destroy.

Refactoring without a destroy/recreate

Moving an existing resource into your new module changes its address, and Terraform treats a new address as a different object — so a naive refactor plans a destroy and recreate of live config. Avoid that with a moved block, which maps the old address to the new one and updates state without touching the device:

moved {
  from = iosxe_vlan.sales
  to   = module.branch_dublin.iosxe_vlan.site["10"]
}

Run terraform plan and confirm it reports a move, not create/destroy, before applying. (When you genuinely do want to rebuild one object — a device left in a bad state — terraform apply -replace=ADDRESS is the supported way, having replaced the old terraform taint command.)

Key takeaways

  • A module is a directory of .tf files with typed inputs and documented outputs; factor repeated designs into one and call it with different inputs. main.tf / variables.tf / outputs.tf is the standard shape.
  • Terraform derives apply order from references between resources and parallelizes the rest, so file and block order never matter; use depends_on only for ordering no reference expresses.
  • The lifecycle block controls replacement: create_before_destroy avoids outage gaps, prevent_destroy guards critical objects, ignore_changes yields fields another system owns, and replace_triggered_by rebuilds on an upstream change.
  • Read plan replace symbols — -/+ destroys first, +/- creates first — and refactor resources into modules with a moved block so you never destroy live config to reorganize code.

Sources: Terraform standard module structure, the lifecycle meta-argument, depends_on, and refactoring with moved blocks.