IaC Core
The dependency graph
Lesson 3 of 5
What you'll learn
- See how attribute references create implicit dependencies
- Understand Terraform's resource graph as a DAG
- Know why ordering (and parallelism) falls out of topological sort
You almost never declare order explicitly. When one resource references another's attribute, Terraform infers an implicit dependency — the referenced resource must exist first.
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
resource "aws_subnet" "app" {
vpc_id = aws_vpc.main.id # depends on the VPC
cidr_block = "10.0.1.0/24"
}
A DAG, not a script
Terraform compiles every resource and reference into a directed acyclic graph. Nodes are resources; edges are dependencies. Because it's a graph and not a top-to-bottom script, Terraform can apply independent branches in parallel while still respecting every edge.
terraform graph | dot -Tsvg > graph.svg # visualize the DAG
Topological order drives everything
To apply, Terraform walks the graph in topological order: a resource is only created after everything it depends on. Destroys run in the reverse order. A cycle — A needs B and B needs A — is unresolvable, and Terraform rejects it at plan time.
Use depends_on sparingly
Reach for explicit depends_on only when a dependency is real but invisible to Terraform (e.g. an IAM policy that must exist before an app can assume a role). Overusing it serializes work that could have run in parallel.
Run it. Order resources so each appears only after its dependencies; a cycle is reported.
How does Terraform usually learn that one resource must be created before another?
Saved on this device. Sign in to sync your progress everywhere.