The Dependency Graph
You never tell the tool in which order to create things. It builds a graph: every resource, data source, variable, output, module and provider is a node, and every reference (aws_vpc.main.id) is an edge. It then walks the graph, doing independent nodes in parallel (10 at a time by default) and dependent ones in order. Destroy walks the same graph backwards.
Seeing the graph
graph prints the graph in Graphviz DOT format. The two CLIs draw it differently, which makes a good comparison: Terraform 1.17 prints a simplified graph of resources only, OpenTofu the full graph including the provider node and its "close" step.
mkdir g && cd g
cat > main.tf <<'HCL'
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
resource "aws_subnet" "app" {
vpc_id = aws_vpc.main.id # reference = edge to aws_vpc.main
cidr_block = "10.0.1.0/24"
}
resource "aws_security_group" "app" {
vpc_id = aws_vpc.main.id
}
resource "aws_s3_bucket" "logs" { # no references: independent
bucket = "linkly-logs"
}
HCL
terraform init >/dev/null
echo "--- terraform graph"
terraform graph
rm -rf .terraform .terraform.lock.hcl && tofu init >/dev/null
echo "--- tofu graph (edges only)"
tofu graph | grep -- '->'--- terraform graph
digraph G {
rankdir = "RL";
node [shape = rect, fontname = "sans-serif"];
"aws_s3_bucket.logs" [label="aws_s3_bucket.logs"];
"aws_security_group.app" [label="aws_security_group.app"];
"aws_subnet.app" [label="aws_subnet.app"];
"aws_vpc.main" [label="aws_vpc.main"];
"aws_security_group.app" -> "aws_vpc.main";
"aws_subnet.app" -> "aws_vpc.main";
}
--- tofu graph (edges only)
"[root] aws_s3_bucket.logs (expand)" -> "[root] provider[\"registry.opentofu.org/hashicorp/aws\"]"
"[root] aws_security_group.app (expand)" -> "[root] aws_vpc.main (expand)"
"[root] aws_subnet.app (expand)" -> "[root] aws_vpc.main (expand)"
"[root] aws_vpc.main (expand)" -> "[root] provider[\"registry.opentofu.org/hashicorp/aws\"]"
"[root] provider[\"registry.opentofu.org/hashicorp/aws\"] (close)" -> "[root] aws_s3_bucket.logs (expand)"
"[root] provider[\"registry.opentofu.org/hashicorp/aws\"] (close)" -> "[root] aws_security_group.app (expand)"
"[root] provider[\"registry.opentofu.org/hashicorp/aws\"] (close)" -> "[root] aws_subnet.app (expand)"
"[root] root" -> "[root] provider[\"registry.opentofu.org/hashicorp/aws\"] (close)"
Read the edges as "needs": aws_subnet.app -> aws_vpc.main means the subnet needs the VPC. To get a picture, pipe the output to Graphviz: tofu graph | dot -Tsvg > graph.svg. graph -type=plan-destroy shows the destroy order.
How the walk works
The model below takes the same four resources, plus an EC2 instance that needs the subnet and the security group, and walks the graph the way the CLI does: at every step it starts everything whose dependencies are done, limited by parallelism.
deps = {
"aws_vpc.main": [],
"aws_s3_bucket.logs": [],
"aws_subnet.app": ["aws_vpc.main"],
"aws_security_group.app": ["aws_vpc.main"],
"aws_instance.web": ["aws_subnet.app", "aws_security_group.app"],
}
def waves(deps, parallelism):
done, order = set(), []
while len(done) < len(deps):
ready = sorted(n for n, d in deps.items() if n not in done and all(x in done for x in d))
batch = ready[:parallelism]
if not batch:
raise ValueError("cycle!")
order.append(batch)
done.update(batch)
return order
for p in (10, 1):
print(f"create, parallelism={p}:")
for i, batch in enumerate(waves(deps, p), 1):
print(f" step {i}: {', '.join(batch)}")
reverse = {n: [m for m, d in deps.items() if n in d] for n in deps}
print("destroy (reverse edges):")
for i, batch in enumerate(waves(reverse, 10), 1):
print(f" step {i}: {', '.join(batch)}")create, parallelism=10:
step 1: aws_s3_bucket.logs, aws_vpc.main
step 2: aws_security_group.app, aws_subnet.app
step 3: aws_instance.web
create, parallelism=1:
step 1: aws_s3_bucket.logs
step 2: aws_vpc.main
step 3: aws_security_group.app
step 4: aws_subnet.app
step 5: aws_instance.web
destroy (reverse edges):
step 1: aws_instance.web, aws_s3_bucket.logs
step 2: aws_security_group.app, aws_subnet.app
step 3: aws_vpc.main
With the default parallelism, the bucket is created alongside the VPC, and the subnet alongside the security group: three steps instead of five. Destroy removes the instance first and the VPC last, because a VPC with subnets in it can't be deleted. You can lower the limit with -parallelism=N when an API rate-limits you.
When references aren't enough: depends_on
Sometimes a dependency is real but invisible in the code. The classic case: an EC2 instance's startup script reads from S3, so it needs the IAM policy attachment, but the instance only references the instance profile:
resource "aws_instance" "worker" {
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
iam_instance_profile = aws_iam_instance_profile.worker.name
# the boot script calls S3; the policy must be attached before the instance starts
depends_on = [aws_iam_role_policy_attachment.worker_s3]
}Use depends_on sparingly and add a comment saying why. It makes the tool more conservative (it can treat more values as unknown until apply), and most "ordering bugs" are better fixed by referencing the right attribute.
Cycles (A needs B, B needs A) are errors. The usual example is two security groups that allow traffic from each other: break it by moving the rules into separate aws_vpc_security_group_ingress_rule resources, which depend on both groups (Security Groups in Code).
Test yourself
How does the CLI know a subnet must be created after its VPC?
- Resources are created in file order
- The subnet references
aws_vpc.main.id, which is an edge in the graph - You must add
depends_on - Alphabetical order
In which order does destroy remove a VPC and its subnets?
- VPC first
- Subnets first, VPC last
- All at once
- Random
When is depends_on the right tool?
- For every resource, to be safe
- When a dependency exists but isn't expressed by any reference, e.g. a policy attachment a boot script needs
- To make apply faster
- To break a cycle