← Lessons/Dependencies & the Resource Graph

Dependencies & the Resource Graph

Terraform doesn't run your file top-to-bottom. Before it changes anything it builds a dependency graph of your resources and walks it in order — creating things that are depended on first, and creating independent things in parallel. Understanding that graph is what lets you reason about what happens when.

There are two ways an edge gets into that graph: a reference (implicit) and depends_on (explicit). Each mini lesson builds on the state the one before it left, so they unlock in order.

dependenciesresource-graphdepends_onreferences

Interview prep

Interviewers love the dependency graph because it reveals whether you understand how Terraform actually executes.

What's the difference between an implicit and an explicit dependency?

An implicit dependency is created when one resource references another's attribute (e.g. network_id = demo_network.main.id) — Terraform infers the order from the reference. An explicit dependency is declared with the depends_on meta-argument when one resource must come after another but doesn't use any of its values. Both add an edge to the graph; references are preferred because they're self-documenting.

When should you use depends_on, and when should you avoid it?

Use it only for a hidden dependency — an ordering requirement Terraform can't infer because no value flows between the resources (e.g. an app that must start after a database it discovers at runtime). Avoid it when you already reference the other resource: the reference creates the edge, so the depends_on is redundant and can even mask the real relationship.

How does Terraform decide what order to create resources in?

It builds a directed dependency graph from references and depends_on, then creates resources so that every dependency comes first; independent resources are created in parallel. There's no implicit top-to-bottom file order — only the graph matters.