What is the main purpose of using depends_on in a Terraform resource configuration?
Think about situations where Terraform might not know which resource to create first.
depends_on tells Terraform explicitly which resources must be created or destroyed before others, ensuring correct order when implicit dependencies are not detected.
Given the following Terraform snippet, what will be the order of resource creation?
resource "aws_instance" "web" {
ami = "ami-123456"
instance_type = "t2.micro"
}
resource "aws_eip" "ip" {
instance = aws_instance.web.id
depends_on = [aws_instance.web]
}Look at the depends_on and the implicit reference inside aws_eip.
The aws_eip.ip resource depends explicitly on aws_instance.web, so Terraform creates the instance first, then the Elastic IP.
You have three resources: db, app, and monitoring. The app must be created after db, and monitoring must be created after both db and app. Which depends_on configuration correctly enforces this?
Think about the order: db → app → monitoring.
Setting app depends_on = [db] ensures app waits for db. Setting monitoring depends_on = [db, app] ensures monitoring waits for both.
You have a security group resource and an instance resource. The instance uses the security group ID. If you forget to add depends_on for the instance on the security group, what could happen?
Consider if Terraform can always detect dependencies from resource attributes.
If the instance references the security group ID directly, Terraform usually detects the dependency. But if the reference is indirect or missing, missing depends_on can cause creation order issues and failures.
Consider two Terraform resources: resource "aws_lb" "load_balancer" and resource "aws_lb_target_group" "target_group". The load balancer depends on the target group using depends_on. When destroying the infrastructure, what is the destruction order?
Think about how depends_on affects destruction order compared to creation order.
depends_on ensures the load balancer is created after the target group, so during destruction, Terraform destroys the load balancer first, then the target group.