TExcelTAD

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.

bash · try it yourself
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.

python · try it yourself
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:

hcl
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?

  1. Resources are created in file order
  2. The subnet references aws_vpc.main.id, which is an edge in the graph
  3. You must add depends_on
  4. Alphabetical order

In which order does destroy remove a VPC and its subnets?

  1. VPC first
  2. Subnets first, VPC last
  3. All at once
  4. Random

When is depends_on the right tool?

  1. For every resource, to be safe
  2. When a dependency exists but isn't expressed by any reference, e.g. a policy attachment a boot script needs
  3. To make apply faster
  4. To break a cycle