How does Terraform handle dependencies between resources?
Answer
Terraform automatically handles resource dependencies through two mechanisms. Implicit dependencies (preferred): when one resource references another's attribute, Terraform infers a dependency and creates/updates them in the correct order. resource "aws_eip" "ip" { instance = aws_instance.web.id } — Terraform knows to create the instance before the EIP. Explicit dependencies: use depends_on when the dependency cannot be inferred from attribute references — typically for IAM policies that need to exist before a resource that uses them but aren't referenced directly. resource "aws_instance" "web" { depends_on = [aws_iam_role_policy.web_policy] }. Terraform builds a dependency graph (DAG) and applies resources in topological order, running independent resources in parallel. The terraform graph command outputs a DOT format visualization of the dependency graph. Circular dependencies cause a validation error.
More Terraform / IaC Questions
View all →- Advanced What is Terraform's provider development and custom providers?
- Advanced What is Policy as Code with Sentinel in Terraform?
- Advanced What is the Terraform CDK (CDKTF)?
- Advanced What are advanced Terraform state management operations?
- Advanced How do you implement a CI/CD pipeline for Terraform?