Skip to Content

Terraform Field Guide · Chapter 5 of 12

Data sources and the dependency graph

You never tell Terraform what order to build things in. It works it out from your references, builds a graph, and runs everything it can in parallel. Learn how to read from the outside world with data sources, how the graph is built, when you need depends_on, and how to untangle a cycle.

  • 40 min
  • Intermediate
  • Hands-on
  • Free

By , founding engineer running Terraform in production. Updated .

aws_vpc.maindata.aws_amiaws_s3_bucketsubnet.asubnet.bsecurity_groupaws_lb.webaws_instanceroute53_recordwave 1wave 2wave 3wave 4destroy runs it backwardsrecord → lb → subnets → vpc
The chapter in one pictureReferences draw the graph. Terraform runs everything it can in parallel, and destroys in reverse.

By the end you can

0 of 5

Data sources: reading what already exists

Not everything you need is something you create. The latest Ubuntu image, the availability zones in a region, the AWS account you are in, a VPC another team owns: these already exist. A data source looks them up so you can use their attributes, without Terraform managing them.

main.tf
data "aws_availability_zones" "available" {
  state = "available"
}

data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"] # Canonical

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"]
  }
}

resource "aws_subnet" "app" {
  vpc_id            = aws_vpc.main.id
  cidr_block        = cidrsubnet(aws_vpc.main.cidr_block, 8, 1)
  availability_zone = data.aws_availability_zones.available.names[0]
}

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.small"
  subnet_id     = aws_subnet.app.id
}
A data block: same shape as a resource, but the address starts with data., and it only reads.
Canonical's AWS account. Always filter images by owner, or anyone could publish an image with a matching name.
Pick the newest match. Handy, but it means a new image can appear in your plan on any day. Pin an ID for production if that matters.
Use a data source like any other attribute.
The instance now depends on the lookup, just as it depends on the subnet.

In a plan, data sources that have to be read during apply show with <=. Most are read during plan, so you see their values straight away.

References are dependencies

Look at the code above again. Nowhere does it say "create the subnet, then the instance". It does not need to: subnet_id = aws_subnet.app.id cannot be filled in until the subnet exists, so Terraform draws an arrow from the instance to the subnet. Every reference is an arrow. Together, the arrows form a dependency graph.

Three rules fall out of the graph:

  • File order means nothing. Split code across files however you like; Terraform reads all .tf files in the folder as one.
  • No arrow means parallel. Things that do not depend on each other are created at the same time, up to 10 at once (change it with -parallelism).
  • Destroy is the graph in reverse. The instance goes before its subnet, the subnet before its VPC. State remembers the arrows, so this works even after you delete the code.

The graph, in action

Here is a small web stack, laid out by the graph Terraform would build. Apply it, destroy it, then break one reference and apply again.

Interactive · The dependency graph

Ten blocks, no order written anywhere. Who goes first?

The timings show why the graph matters in practice. A database takes several minutes to provision and a load balancer a couple; because neither needs the other, they are built at the same time instead of one after the other. And the broken case is real: hard-coding an ID copied from the console both removes the edge and ties the code to one environment.

depends_on: for dependencies Terraform cannot see

Sometimes a dependency is real but no attribute expresses it. The classic case: an instance whose software reads from S3 at boot, through an IAM policy attached to its role. The instance references the instance profile, not the policy, so Terraform may launch it before the policy exists, and the app fails its first start.

app.tf
resource "aws_iam_role_policy" "app_s3" {
  role   = aws_iam_role.app.id
  policy = data.aws_iam_policy_document.app_s3.json
}

resource "aws_instance" "app" {
  ami                  = data.aws_ami.ubuntu.id
  instance_type        = "t3.small"
  iam_instance_profile = aws_iam_instance_profile.app.name

  # The app reads from S3 the moment it boots. Nothing in this block
  # references the policy, so say so explicitly.
  depends_on = [aws_iam_role_policy.app_s3]
}
An explicit edge. The instance now waits for the policy, as if it referenced it.
Always leave a comment. Without one, the next person will either delete it or copy it everywhere.

Cycles

A graph needs a starting point. If A needs B and B needs A, there is none, and Terraform stops before planning:

terraform plan
terraform plan
│ Error: Cycle: aws_security_group.db, aws_security_group.web

The usual cause is two security groups with inline rules that point at each other: web may talk to db, db accepts web. The fix is to stop the groups referencing each other, and put each rule in a resource of its own:

security.tf
resource "aws_security_group" "web" {
  vpc_id = aws_vpc.main.id
}

resource "aws_security_group" "db" {
  vpc_id = aws_vpc.main.id
}

# One rule per resource: each side references the other group,
# but the groups themselves no longer reference each other.
resource "aws_vpc_security_group_ingress_rule" "db_from_web" {
  security_group_id            = aws_security_group.db.id
  referenced_security_group_id = aws_security_group.web.id
  ip_protocol                  = "tcp"
  from_port                    = 5432
  to_port                      = 5432
}

resource "aws_vpc_security_group_egress_rule" "web_to_db" {
  security_group_id            = aws_security_group.web.id
  referenced_security_group_id = aws_security_group.db.id
  ip_protocol                  = "tcp"
  from_port                    = 5432
  to_port                      = 5432
}
The groups only need the VPC now. No cycle.
A separate rule resource. It depends on both groups, and nothing depends on it.

The same move, pulling the shared part out into a third resource, fixes most cycles you will meet.

Hands-on: draw your own graph

A local configuration with a data source, a reference and one independent resource. First create the file the data source will read:

Set up
echo "maintenance on Sundays" > motd.txt
main.tf
terraform {
  required_providers {
    local  = { source = "hashicorp/local", version = "~> 2.5" }
    random = { source = "hashicorp/random", version = "~> 3.6" }
  }
}

data "local_file" "motd" {
  filename = "${path.module}/motd.txt"
}

resource "random_pet" "server" {}

resource "local_file" "inventory" {
  filename = "${path.module}/inventory.txt"
  content  = "${random_pet.server.id}: ${data.local_file.motd.content}"
}

resource "local_file" "readme" {
  filename = "${path.module}/README.txt"
  content  = "Generated by Terraform."
}
Reads a file Terraform does not manage. Delete motd.txt and the plan fails: a data source must find what it looks for.
A reference to a data source: inventory now depends on it and on random_pet.
References nothing, so it has no dependencies and is created in parallel with the rest.
Apply and look at the graph
terraform init
terraform apply -auto-approve
terraform graph
random_pet.server: Creating...
local_file.readme: Creating...
random_pet.server: Creation complete after 0s [id=proud-gecko]
local_file.readme: Creation complete after 0s [id=36390907da67...]
local_file.inventory: Creating...
local_file.inventory: Creation complete after 0s [id=01e92ba1f90b...]

digraph G {
  rankdir = "RL";
  node [shape = rect, fontname = "sans-serif"];
  "data.local_file.motd" [label="data.local_file.motd"];
  "local_file.inventory" [label="local_file.inventory"];
  "local_file.readme" [label="local_file.readme"];
  "random_pet.server" [label="random_pet.server"];
  "local_file.inventory" -> "data.local_file.motd";
  "local_file.inventory" -> "random_pet.server";
}
Creating...
random_pet and readme start together; inventory waits for both its dependencies.
terraform graph
Prints the graph in DOT format. Paste it into any Graphviz viewer, or run terraform graph | dot -Tsvg > graph.svg if you have Graphviz installed.
local_file.readme
A node with no arrows: nothing depends on it, and it depends on nothing.

Mini mission

Make a cycle, then break it

Add two local_file resources, a and b, where each one's content includes the other's filename. Run plan and read the error. Then change the code so both files still mention each other's name, without a cycle.

Reveal one safe solution
main.tf
locals {
  a_name = "${path.module}/a.txt"
  b_name = "${path.module}/b.txt"
}

resource "local_file" "a" {
  filename = local.a_name
  content  = "see ${local.b_name}"
}

resource "local_file" "b" {
  filename = local.b_name
  content  = "see ${local.a_name}"
}

The first version fails with Error: Cycle: local_file.b, local_file.a. Moving the shared values into locals removes the arrows between the two files: each depends only on the locals, which depend on nothing. Same trick as the security group rules, pull the shared part out.

Check yourself

Quiz

0 of 5 answered

  1. 1. What does a data source do?
  2. 2. How does Terraform know to create a subnet before the instance inside it?
  3. 3. Two resources do not reference each other at all. What does apply do with them?
  4. 4. When is depends_on the right tool?
  5. 5. Terraform reports "Error: Cycle". What does that mean?

Further reading