Resource Meta-Arguments: depends_on
You'll learn how to use depends_on to explicitly define resource dependencies when Terraform can't figure them out automatically.
The Problem with Implicit Dependencies
Terraform is smart—it automatically understands when one resource needs another by analyzing attribute references. For example, if a resource uses aws_instance.web.id, Terraform knows to create the instance first. But sometimes resources depend on each other in ways that aren't visible through direct attribute references.
What is depends_on?
The depends_on meta-argument lets you manually tell Terraform: "Don't create this resource until these other resources exist." Think of it like telling a friend, "Don't start decorating the cake until I've finished baking it," even though decorating doesn't technically use any ingredients from baking.
When You Need It
Use depends_on when:
- A resource must exist before another, but no attributes are referenced
- Side effects or timing matter (like waiting for a service to be fully operational)
- External dependencies require a specific creation order
Basic Syntax
resource "aws_instance" "app" {
ami = "ami-123456"
instance_type = "t2.micro"
depends_on = [
aws_iam_role_policy.app_policy,
aws_s3_bucket.data
]
}
Here, the EC2 instance waits for both the IAM policy and the S3 bucket to be created first, even though it doesn't directly reference their attributes.
The Trade-off
While depends_on gives you control, use it sparingly. Overusing it can slow down parallel resource creation and hide the real relationships in your infrastructure.
Key Takeaway: Use depends_on to explicitly control resource creation order when implicit dependencies through attribute references aren't sufficient—it's your manual override for Terraform's automatic dependency graph.