Terraform Tutorial — Resource Dependencies
Terraform automatically figures out the order to create resources based on their dependencies. If a security group references a VPC, Terraform knows to create the VPC first. This page covers both implicit and explicit dependencies.
Implicit Dependencies
When one resource references an attribute of another, Terraform creates an implicit dependency:
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
resource "aws_subnet" "public" {
vpc_id = aws_vpc.main.id # ← References VPC's id
cidr_block = "10.0.1.0/24"
}
Terraform sees that aws_subnet.public uses aws_vpc.main.id and automatically:
- Creates the VPC first
- Waits for the VPC to be ready
- Creates the subnet with the VPC’s ID
You don’t need to tell Terraform about this dependency — the reference creates it automatically.
Dependency Graph
Terraform builds an internal dependency graph of all resources. You can visualize it:
$ terraform graph | dot -Tpng > graph.png
For a simple VPC + subnet setup, the graph shows:
aws_vpc.main ──▶ aws_subnet.public
Terraform uses this graph to:
- Create resources in the correct order
- Update dependent resources when a dependency changes
- Destroy resources in reverse order
Explicit Dependencies with depends_on
Sometimes there’s a dependency that Terraform can’t detect from references alone. Use depends_on for these:
resource "aws_s3_bucket" "logs" {
bucket = "my-app-logs"
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
depends_on = [aws_s3_bucket.logs]
}
💡 Tip: Use
depends_onsparingly. If you need it, ask yourself: “Can I express this dependency through a reference instead?” Implicit dependencies through references are clearer and less error-prone.
When to Use depends_on
| Scenario | Use depends_on? |
|---|---|
| Resource B uses an attribute from Resource A | No — implicit dependency via reference |
| Resource B must exist before Resource A works, but there’s no attribute reference | Yes |
| IAM policy must be attached before an instance can use it | Yes (sometimes) |
| S3 bucket must exist before a Lambda that writes to it | Depends — if the Lambda config references the bucket ARN, no |
Circular Dependencies
If Resource A depends on Resource B, and Resource B depends on Resource A, Terraform reports an error:
Error: Cycle: aws_security_group.a, aws_security_group.b
Fix circular dependencies by:
- Restructuring your resources to remove the cycle
- Using
aws_security_group_ruleas separate resources instead of inline rules
What’s Next?
You understand how Terraform orders resource creation. Next, let’s look at the lifecycle block — controlling how Terraform handles resource updates and deletions.