🧩 Depends On in Terraform: Define Explicit Resource Dependencies


Terraform, as an Infrastructure as Code (IaC) tool, automates the process of provisioning cloud infrastructure. One of its most powerful features is dependency management — ensuring resources are created or destroyed in the correct order.

While Terraform automatically determines dependencies from resource references, there are times when we need to manually specify the dependency order. That’s where the depends_on meta-argument comes in.


🔹 What is depends_on in Terraform?

The depends_on argument explicitly declares that a resource must be created only after one or more other resources have been successfully created.

Terraform usually infers relationships automatically based on references (like one resource using the ID of another), but depends_on gives you full control when such implicit connections don’t exist.


🔹 Why Do We Need depends_on?

Imagine you are creating:

  • An S3 bucket, and
  • An IAM policy that applies to that bucket.

Terraform might not automatically detect that the policy depends on the bucket (if not directly referenced). In such cases, you can manually enforce order using depends_on.


⚙️ Syntax

resource "resource_type" "name" {
# resource configuration
depends_on = [
resource_type.resource_name,
another_resource_type.another_resource_name
]
}

You can specify multiple dependencies in a list.


🔹 Terraform’s Dependency Model

Terraform automatically builds a Dependency Graph, a visual map of how resources depend on each other. Using depends_on, you can inject additional relationships into this graph to control execution order.


🧭 ** Dependency Flow**

VPC Creation

Subnet Creation

EC2 Instance Launch

Security Group

depends_on MetaArgument

Deployment Success

Explanation:

  • Terraform creates a VPC first.
  • Then Subnets, followed by the EC2 Instance.
  • depends_on ensures that certain tasks occur only after prerequisite resources are ready.

🔹 Real-World Analogy

Think of Terraform dependencies like building a house:

  • You can’t install windows before walls exist.
  • You can’t paint before walls are finished.
  • depends_on ensures that Terraform builds “walls before windows”.

🧱 1️⃣ Example 1: AWS S3 Bucket and IAM Policy

Let’s start with a simple but practical example.

Terraform Code Example

resource "aws_s3_bucket" "app_bucket" {
bucket = "myapp-storage-bucket"
}
resource "aws_iam_policy" "bucket_policy" {
name = "S3BucketAccessPolicy"
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Action = ["s3:GetObject"],
Effect = "Allow",
Resource = "${aws_s3_bucket.app_bucket.arn}/*"
}]
})
depends_on = [
aws_s3_bucket.app_bucket
]
}

🧩 Explanation:

  • The IAM policy depends on the bucket’s existence.
  • depends_on ensures Terraform creates the S3 bucket first before applying the IAM policy.

🧠 Key Takeaway:

“Bucket before policy — dependency makes it jolly!”


🧱 2️⃣ Example 2: EC2 Instance After Security Group

When launching an EC2 instance, it must wait for its Security Group to be created.

Terraform Code Example

resource "aws_security_group" "web_sg" {
name = "web-security-group"
description = "Allow web traffic"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_instance" "web_server" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "WebServer"
}
depends_on = [
aws_security_group.web_sg
]
}

🧩 Explanation:

  • Terraform ensures that the Security Group is created first.
  • The EC2 Instance only launches once it’s ready.

🧠 Memory Tip:

“Server waits for shield — security before field!”


🧱 3️⃣ Example 3: Database Initialization Script

Suppose you’re creating a PostgreSQL database and need to run an initialization script after the database is ready.

Terraform Code Example

resource "aws_db_instance" "postgres_db" {
identifier = "myapp-postgres"
allocated_storage = 20
engine = "postgres"
instance_class = "db.t3.micro"
username = "admin"
password = "secret123"
skip_final_snapshot = true
}
resource "null_resource" "init_script" {
provisioner "local-exec" {
command = "psql -h ${aws_db_instance.postgres_db.address} -U admin -f ./init.sql"
}
depends_on = [
aws_db_instance.postgres_db
]
}

🧩 Explanation:

  • The script runs only after the PostgreSQL instance is created and available.
  • Without depends_on, Terraform might attempt to execute the script too early, causing errors.

🧠 Memory Trick:

“No script before DB — let the server breathe free!”


🔹 Execution Order

Null Resource Init ScriptAWS DB InstanceTerraformNull Resource Init ScriptAWS DB InstanceTerraformCreate PostgreSQL DBDB CreatedRun Init Script depends_on

Explanation: Terraform ensures the DB is created before executing the script.


🔹 Common Use Cases for depends_on

Use CaseResource TypePurpose
Security Groups before EC2AWSPrevent premature instance creation
Network before Load BalancerGCP / AWSEnsure connectivity before routing
Bucket before IAM PolicyAWSPrevent missing resource errors
Database before InitializationAWS / AzureSequence data setup correctly
Key Vault before Secret UploadAzureEnsure vault exists first

🔹 Implicit vs. Explicit Dependencies

Terraform automatically detects dependencies when:

  • A resource references another resource’s attributes.

Example of Implicit Dependency:

resource "aws_instance" "app" {
subnet_id = aws_subnet.public.id
}

Here, Terraform knows that aws_instance depends on aws_subnet automatically.

However, when there’s no direct reference, use depends_on to enforce order manually.


🔹 Advantages of Using depends_on

BenefitExplanation
Order ControlEnsures Terraform creates resources in the correct order
Error PreventionPrevents “resource not found” or “dependency missing” errors
Infrastructure StabilityGuarantees dependent resources are ready
Better DebuggingHelps identify the flow of creation/destruction

🔹 Terraform Dependency Graph

Yes

No

Terraform Plan

Build Dependency Graph

Has depends_on?

Add Manual Dependency

Use Implicit References

Apply Resources in Order

Infrastructure Stable and Error-Free


🔹 How to Remember depends_on for Interviews

🎓 Mnemonic: “D.O.N.E.”

LetterStands ForMeaning
DDefine dependenciesExplicitly declare resource relationships
OOrder controlManage creation order manually
NNo early runsPrevent premature executions
EError-free buildsEnsure stable deployments

💡 Phrase:

“When you’re D.O.N.E. with errors, use depends_on!”


🔹 Best Practices

1. Use only when necessary Terraform already tracks dependencies automatically. Avoid overusing depends_on as it can complicate dependency graphs.

2. Keep dependencies simple Too many dependencies can slow down plan/apply steps.

3. Comment your dependencies Document why each dependency exists for clarity.

4. Test dependency chains Use terraform plan to validate creation order.

5. Avoid circular dependencies Terraform cannot resolve recursive dependency loops.


🔹 Common Mistakes

MistakeDescriptionSolution
Using depends_on unnecessarilyOvercomplicates the planUse only for non-referenced resources
Forgetting depends_on for scriptsCauses early executionAdd explicit dependency
Circular dependenciesTwo resources depend on each otherRedesign dependency structure
Ignoring dynamic dependenciesDependencies may change with variablesKeep flexible configurations

🔹 Why It’s Important to Learn depends_on

ReasonExplanation
Core DevOps SkillManaging dependencies is essential for stable automation
Error PreventionPrevents “resource not ready” failures
Cloud PortabilityWorks across AWS, Azure, and GCP
Exam & Interview RelevanceFrequently asked in Terraform certification
Production ReliabilityAvoids race conditions and failed deployments

🔹 Real-World Scenarios

🌍 Scenario 1: Infrastructure Sequencing

A web app needs:

  1. VPC → 2. Subnet → 3. Load Balancer → 4. EC2

Without depends_on, Terraform may deploy in the wrong sequence.

🧰 Scenario 2: Data Initialization

Database seeding scripts must wait for DB creation.

🔐 Scenario 3: Security Dependencies

Security groups and IAM roles must exist before launching dependent instances.


🔹 Terraform and the DAG (Directed Acyclic Graph)

Terraform uses a DAG (Directed Acyclic Graph) internally to manage resource creation order.

depends_on directly influences this DAG:

  • Adds explicit edges between nodes (resources)
  • Ensures Terraform knows the exact sequence

📊 — DAG Visualization

VPC

Subnet

Security Group

EC2 Instance

Database

Explanation: Terraform’s DAG ensures resources follow logical dependency paths without cycles.


🔹 Terraform depends_on with Modules

depends_on can also be applied at the module level, not just resources.

Example:

module "network" {
source = "./modules/network"
}
module "application" {
source = "./modules/app"
depends_on = [module.network]
}

Explanation: The application module will deploy only after the network module completes.


🔹 Interview Preparation Guide

Common Questions:

  1. What is the purpose of depends_on in Terraform?
  2. What is the difference between implicit and explicit dependencies?
  3. Can you use depends_on in modules?
  4. What happens if you forget to use depends_on?
  5. How does Terraform’s DAG relate to dependencies?

Tips to Answer:

  • Start with definition, then use case, followed by example.
  • Mention it’s useful when implicit references aren’t available.
  • Always note it affects the DAG (Directed Acyclic Graph).

🔹 How to Practice for Exams

  1. Build small examples — create 2–3 resources with and without depends_on.
  2. Run terraform plan — observe how creation order changes.
  3. Use terraform graph — visualize the dependency graph.
  4. Simulate failures — remove depends_on and see what breaks.
  5. Take notes — summarize each case in one line.

🔹 Summary Diagram — Lifecycle with depends_on

Implicit

Explicit depends_on

Define Resources

Terraform Plan

Dependencies?

Terraform Infers Automatically

Manual Dependency Set

Build DAG

Apply in Correct Order


🔹 Quick Recap

ConceptExplanationExample
depends_onEnforces resource orderEC2 after Security Group
Implicit DependencyTerraform infers automaticallyResource references
Explicit DependencyManually declareddepends_on = [resource.name]
Best PracticeUse when references don’t existScript or policy cases

🧠 Final Mnemonic Recap

“D.O.N.E. with errors? Use depends_on!” Define → Order → No errors → Explicit dependency


The depends_on argument is a powerful but simple control mechanism in Terraform that ensures resources are deployed in the right order. By defining explicit dependencies, you can avoid timing issues, race conditions, and deployment failures.

It’s not just a feature—it’s a best practice for reliable, production-grade infrastructure management.

🚀 Key Takeaway: “Terraform builds your world in order — and depends_on is the conductor of that orchestration.”