When should you add `depends_on`, and what can go wrong with it?
AdvancedScenarioResources Variables and Expressions
Answer
Situation read → Terraform infers most dependencies from references; explicit ones are for hidden dependencies.
What I'd do →
- Use it only when the dependency isn't visible in an attribute reference, such as an IAM policy that must exist before an instance starts.
- Avoid
depends_onon modules or data sources unless essential.
resource "aws_instance" "app" {
# ...
depends_on = [aws_iam_role_policy.app]
}
Why → depends_on on a data source defers its read to apply time, so values become unknown at plan time and downstream diffs get noisy. On modules it makes everything in the module wait.
Interview tip → Prefer expressing the dependency through a real reference.
More on Resources Variables and Expressions
You need three identical web servers. How do you declare them, and what is the catch with `count`?BeginnerYou manage subnets from a list of CIDRs. Someone removes the second CIDR and Terraform plans to recreate the third subnet. Why, and what do you change?IntermediateHow do you stop someone passing `environment = "production"` when only `dev`, `stage` and `prod` are valid?BeginnerA module takes a database password and exposes the connection string as an output. How do you stop them leaking into plan output?BeginnerA monitoring stack should only exist in prod. How do you create a resource conditionally?BeginnerYou have subnets defined as `{ web = {...}, db = {...} }` per VPC, nested two levels deep. How do you create them with `for_each`?Advanced