Q: How does the Terraform dependency graph (DAG) work internally to determine resource execution order and concurrency?
Deep dive into Terraform's internal Directed Acyclic Graph (DAG) construction, topological sort evaluation, concurrency management, and dependency cycle prevention.
🛠️ Production Runbook & Step-by-Step Resolution
Graph Construction & Implicit References
Terraform analyzes references in HCL. When aws_instance.web references aws_security_group.sg.id, Terraform automatically creates a directed edge: sg -> instance. Explicit depends_on directives add manual edges when implicit data references do not exist.
Topological Sorting & Parallel Execution
Terraform performs a topological sort on the DAG to find independent root nodes. Resources with zero incoming dependencies are provisioned in parallel up to the concurrency limit (-parallelism=10 by default).
Detecting Cycles and Visualizing the Graph
If resource A references resource B, and resource B references resource A, Terraform detects a cycle during graph compilation and errors with 'Cycle detected' before touching real infrastructure.
terraform graph | dot -Tpng > graph.png
- Terraform builds a Directed Acyclic Graph where resources are nodes and references are edges.
- Implicit dependencies (attribute references) and explicit depends_on define graph ordering.
- Topological sorting allows independent resources to deploy concurrently (default 10 parallel threads).
- Cycle detection prevents deadlocks before touching any cloud provider APIs.