Terraform
Basics & Fundamentals
- Infrastructure as Code (IaC)
- Declarative Syntax in IaC
- Terraform Configuration Files
- Terraform CLI
- Terraform Init
- Terraform Plan
- Terraform Apply
- Terraform Destroy
Providers & Resources
Variables & Outputs
- Input Variables
- Variable Types
- Default Values
- Environment Variables
- Output Values
- Variable Validation
State Management
- Terraform State File
- Terraform Remote State
- Terraform State Locking
- Terraform Drift Detection
- Terraform Refresh
- Terraform Import
Modules (Reusability)
- Terraform Modules
- Terraform Public Modules
- Terraform local modules
- Terraform Module Versioning
- Terraform Nested Modules
Provisioners & Lifecycle
🧩 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**
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
Explanation: Terraform ensures the DB is created before executing the script.
🔹 Common Use Cases for depends_on
Use Case | Resource Type | Purpose |
---|---|---|
Security Groups before EC2 | AWS | Prevent premature instance creation |
Network before Load Balancer | GCP / AWS | Ensure connectivity before routing |
Bucket before IAM Policy | AWS | Prevent missing resource errors |
Database before Initialization | AWS / Azure | Sequence data setup correctly |
Key Vault before Secret Upload | Azure | Ensure 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
Benefit | Explanation |
---|---|
Order Control | Ensures Terraform creates resources in the correct order |
Error Prevention | Prevents “resource not found” or “dependency missing” errors |
Infrastructure Stability | Guarantees dependent resources are ready |
Better Debugging | Helps identify the flow of creation/destruction |
🔹 Terraform Dependency Graph
🔹 How to Remember depends_on
for Interviews
🎓 Mnemonic: “D.O.N.E.”
Letter | Stands For | Meaning |
---|---|---|
D | Define dependencies | Explicitly declare resource relationships |
O | Order control | Manage creation order manually |
N | No early runs | Prevent premature executions |
E | Error-free builds | Ensure 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
Mistake | Description | Solution |
---|---|---|
Using depends_on unnecessarily | Overcomplicates the plan | Use only for non-referenced resources |
Forgetting depends_on for scripts | Causes early execution | Add explicit dependency |
Circular dependencies | Two resources depend on each other | Redesign dependency structure |
Ignoring dynamic dependencies | Dependencies may change with variables | Keep flexible configurations |
🔹 Why It’s Important to Learn depends_on
Reason | Explanation |
---|---|
Core DevOps Skill | Managing dependencies is essential for stable automation |
Error Prevention | Prevents “resource not ready” failures |
Cloud Portability | Works across AWS, Azure, and GCP |
Exam & Interview Relevance | Frequently asked in Terraform certification |
Production Reliability | Avoids race conditions and failed deployments |
🔹 Real-World Scenarios
🌍 Scenario 1: Infrastructure Sequencing
A web app needs:
- 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
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:
- What is the purpose of
depends_on
in Terraform? - What is the difference between implicit and explicit dependencies?
- Can you use
depends_on
in modules? - What happens if you forget to use
depends_on
? - 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
- Build small examples — create 2–3 resources with and without
depends_on
. - Run
terraform plan
— observe how creation order changes. - Use
terraform graph
— visualize the dependency graph. - Simulate failures — remove
depends_on
and see what breaks. - Take notes — summarize each case in one line.
🔹 Summary Diagram — Lifecycle with depends_on
🔹 Quick Recap
Concept | Explanation | Example |
---|---|---|
depends_on | Enforces resource order | EC2 after Security Group |
Implicit Dependency | Terraform infers automatically | Resource references |
Explicit Dependency | Manually declared | depends_on = [resource.name] |
Best Practice | Use when references don’t exist | Script 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.”