Terraform interview question · Most asked

When do you need depends_on in Terraform, and when is it a code smell?

Comparison Asked in DevOps Engineer · Cloud Engineer · Site Reliability Engineer (SRE) interviews

Members can save this page, take notes and track progress. See membership · Sign in

Summary

You need depends_on when Terraform cannot see the dependency from references alone — most commonly when a resource reads from something created by another resource through a mechanism outside Terraform's graph (like an IAM policy that must exist before an AWS service can use it, but the ARN isn't referenced). In most other cases, implicit dependencies from attribute references are correct and depends_on is unnecessary.

Longer Answer

Terraform builds a dependency graph from attribute references: if resource B uses aws_vpc.main.id, Terraform knows B depends on the VPC. This handles 90% of cases.

When depends_on is necessary:

  1. IAM eventual consistency: a Lambda function references its execution role by ARN, but AWS needs the role's policy to be fully propagated before the function can be invoked. The role ARN reference creates a dependency on the role, but not on the aws_iam_role_policy_attachment that attaches the policy. Adding depends_on on the attachment ensures the policy is attached before the function is created.

  2. Side-effect dependencies: resource A writes to an S3 bucket and resource B reads from it, but B doesn't reference A's attributes — B just hardcodes the same bucket path. Terraform sees no link, so B might run first.

  3. Module-level ordering: depends_on on a module call forces the entire module to wait until the dependency is complete. This is common for "the VPC module must finish before the ECS module starts."

When it's a code smell:

  • If you can express the dependency through an attribute reference, do that instead. depends_on hides the reason for the ordering and makes refactoring harder.
  • Overusing depends_on serialises the plan and slows apply.
  • If you find yourself adding depends_on to fix a race condition, check whether the real fix is passing an output from one resource to another.

Key Points

  • Use depends_on only when the dependency cannot be expressed through attribute references
  • Common case: IAM policy attachments that must propagate before a resource can use the role
  • Module-level depends_on forces the entire module to wait
  • Overuse serialises the graph and slows down plans and applies

Explanation

What interviewers look for

Look for the distinction between implicit (reference-based) and explicit (depends_on) dependencies. Weak answers use depends_on everywhere "to be safe". Strong answers explain that attribute references are preferred and give a concrete example where depends_on is genuinely needed.

More Terraform questions

← All Terraform questions

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake