TERRAFORM

Implicit vs explicit dependencies in Terraform

Understand Terraform's dependency graph, implicit references and the cases where depends_on is useful.

MANISH KUMAR SINGH · DEVOPS NOTES

Implicit dependency

Terraform automatically creates a dependency when one resource references an attribute from another resource. The reference itself tells Terraform which object must exist first.

resource "azurerm_resource_group" "rg" {
  name     = "devops-rg"
  location = "East US"
}

resource "azurerm_storage_account" "app" {
  name                     = "devopsapp123"
  resource_group_name      = azurerm_resource_group.rg.name
  location                 = azurerm_resource_group.rg.location
}

Because the storage account references the resource group's attributes, Terraform knows the relationship without an explicit dependency.

Explicit dependency with depends_on

Use depends_on when the dependency exists operationally but is not visible through a resource attribute reference.

resource "azurerm_role_assignment" "example" {
  # ...
  depends_on = [
    azurerm_role_definition.example
  ]
}

The important point is that depends_on should not be used everywhere. Overusing it can make the graph more restrictive than necessary.

How Terraform uses the graph

Terraform builds a graph of resources and relationships, then walks that graph while respecting dependencies. Independent resources can be processed in parallel, while dependent resources wait for their prerequisites.

Interview tip: Say: “Implicit dependencies come from references in expressions. Explicit dependencies are declared with depends_on when Terraform cannot infer the real operational dependency.”