Terraform 11: Implicit dependencies & depends_on
easy⏱ 5 mincourseterraform
Implicit dependencies from references
When resource B references an attribute of resource A (like azurerm_resource_group.orders.name), Terraform infers that A must exist before B. This is an implicit dependency — you never state the order; the graph derives it from your references and even parallelizes independent branches.
resource "azurerm_resource_group" "orders" {
name = "myorg-orders-dev-rg"
location = "westus2"
}
# References orders.name → Terraform creates the group first, then this.
resource "azurerm_storage_account" "orders" {
name = "myorgordersdev"
resource_group_name = azurerm_resource_group.orders.name
location = azurerm_resource_group.orders.location
account_tier = "Standard"
account_replication_type = "LRS"
}
depends_on for hidden ordering
Sometimes B must wait for A but never references it — e.g. A grants an IAM role that B's runtime needs, with no attribute passing between them. depends_on states that edge explicitly. It takes a list of resource addresses (not strings, not attributes) and should be a last resort: prefer a real reference whenever one exists.
resource "azurerm_role_assignment" "orders_blob" {
scope = azurerm_storage_account.orders.id
role_definition_name = "Storage Blob Data Contributor"
principal_id = var.app_principal_id
}
resource "azurerm_storage_container" "orders" {
name = "uploads"
storage_account_id = azurerm_storage_account.orders.id
container_access_type = "private"
# Wait for the role even though we don't read any of its attributes.
depends_on = [azurerm_role_assignment.orders_blob]
}
Overusing depends_on hurts you
Every unnecessary depends_on serializes work Terraform could have parallelized and can force wider replacements on change. If you catch yourself adding depends_on where an attribute reference would express the same relationship, switch to the reference — it is more precise and self-documenting.
Topologically sort a dependency graph
Given graph mapping each resource to the list it depends on, write creationOrder(graph) returning resources so every dependency comes before its dependents. With rg depending on nothing, storage on rg, and container on storage, log creationOrder(graph).join(" -> ") — it must print rg -> storage -> container.