Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท Providers and Resources

Dependencies and the Resource Graph

Understand implicit and explicit dependencies in Terraform: depends_on, the resource graph, terraform graph, dependency cycles, parallelism and destroy order.

Terraform decides the order of operations by itself, and it decides it from a dependency graph. Most of the time you do nothing: a reference from one resource to another is enough. But sometimes a dependency exists that Terraform cannot see in your code, and sometimes a badly designed configuration creates a loop. Knowing how to handle both cases separates people who "use Terraform" from people who can fix it when an apply fails halfway.

HCL is read-only here; the runnable stand-ins detect cycles, add explicit edges and print the graph in the format Terraform uses.

Implicit dependencies

An implicit dependency comes from a reference:

HCL
resource "aws_iam_role" "app" {
  name               = "app"
  assume_role_policy = data.aws_iam_policy_document.assume.json
}

resource "aws_instance" "app" {
  iam_instance_profile = aws_iam_instance_profile.app.name   # edge: instance -> profile
}

resource "aws_iam_instance_profile" "app" {
  role = aws_iam_role.app.name                               # edge: profile -> role
}

Terraform creates the role, then the instance profile, then the instance, and destroys them in the reverse order. Prefer implicit dependencies: they document themselves, and they also pass data (the name or ID) along the edge.

Explicit dependencies with depends_on

Sometimes resource B needs resource A to exist, but nothing in B's arguments uses A's attributes. The relationship is hidden in how the cloud behaves. A common case: an application that needs an IAM policy to be in place before it starts, where the instance only references the role, not the policy attachment:

HCL
resource "aws_iam_role_policy_attachment" "s3_read" {
  role       = aws_iam_role.app.name
  policy_arn = aws_iam_policy.s3_read.arn
}

resource "aws_instance" "app" {
  iam_instance_profile = aws_iam_instance_profile.app.name

  depends_on = [aws_iam_role_policy_attachment.s3_read]
}

depends_on takes a list of resources, modules or data sources (not attributes, not expressions). It adds an edge without passing a value.

depends_on is a last resort. Its side effects: a dependent data source is deferred to apply time, so its values become unknown at plan time, and a module-level depends_on can make plans larger and replacements more frequent. Comment every use with why it is needed, and remove it when a reference can express the dependency instead.

Seeing the graph

terraform graph prints the graph in DOT format, which Graphviz can draw:

Terminal
terraform graph | dot -Tsvg > graph.svg
TEXT
digraph {
  compound = "true"
  newrank = "true"
  subgraph "root" {
    "[root] aws_instance.app" -> "[root] aws_iam_instance_profile.app"
    "[root] aws_iam_instance_profile.app" -> "[root] aws_iam_role.app"
  }
}

(Example output, shortened.) An arrow A -> B reads "A depends on B". Real graphs also contain nodes for providers and variables, so they get noisy fast. terraform graph -type=plan shows the graph for a plan; the graph is mostly useful for understanding a surprising order or a cycle.

flowchart BT
    R["aws_iam_role.app"]
    P["aws_iam_instance_profile.app"]
    A["aws_iam_role_policy_attachment.s3_read"]
    I["aws_instance.app"]
    P --> R
    A --> R
    I --> P
    I -.->|"depends_on"| A

Solid arrows are references (implicit); the dashed arrow is the explicit depends_on. Arrows point at the thing that must exist first.

Python Explicit edges, DOT output and creation order (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Dependency cycles

A cycle appears when A depends on B and B depends on A (directly or through others). Terraform cannot order them and stops with Error: Cycle: aws_security_group.a, aws_security_group.b. The classic example is two security groups that each allow traffic from the other when the rules are written inline:

HCL
resource "aws_security_group" "app" {
  ingress { security_groups = [aws_security_group.db.id] }   # app needs db
}
resource "aws_security_group" "db" {
  ingress { security_groups = [aws_security_group.app.id] }  # db needs app: cycle
}

The fix is to create the groups first and add the rules as separate resources:

HCL
resource "aws_security_group" "app" { name = "app" }
resource "aws_security_group" "db"  { name = "db" }

resource "aws_vpc_security_group_ingress_rule" "db_from_app" {
  security_group_id            = aws_security_group.db.id
  referenced_security_group_id  = aws_security_group.app.id
  from_port = 5432
  to_port   = 5432
  ip_protocol = "tcp"
}

Splitting a resource into smaller pieces is the general remedy: when two things need each other's identity but not each other's completeness, create the identities first and connect them afterwards.

Python Detecting a cycle (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Parallelism and ordering guarantees

Terraform runs independent nodes concurrently, 10 at a time by default (-parallelism=N). The only ordering guarantees are the edges of the graph. If two resources are not connected, you must not assume one finishes before the other, even if one appears first in the file. Lower -parallelism when an API rate-limits you.

For destroy, the graph is reversed, so dependents go first. If a destroy fails with "DependencyViolation" (for example, a security group still attached to something Terraform does not manage), the problem is usually something outside Terraform holding a reference.

Waiting for eventual consistency

Cloud APIs sometimes return before a change is fully effective, for example IAM policies that take seconds to propagate. A dependency edge guarantees the API call returned, not that the platform is ready. For such cases insert a delay resource:

HCL
resource "time_sleep" "wait_for_iam" {
  depends_on      = [aws_iam_role_policy_attachment.s3_read]
  create_duration = "30s"
}

resource "aws_instance" "app" {
  depends_on = [time_sleep.wait_for_iam]
}

It is ugly but honest, and commenting why avoids someone deleting it.

Data sources and dependencies

A data source that references a managed resource is read during apply, not plan, when the resource is still unknown. That is fine, but it means a plan cannot show the data source's result. This is another reason to avoid depends_on on data sources; see data sources.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which is the preferred way to express that a subnet needs its VPC?

    A reference creates an implicit dependency and passes the needed ID. depends_on is only for hidden dependencies.
  2. 2. What can go in a depends_on list?

    depends_on accepts references to resources, data sources and modules, not individual attributes.
  3. 3. Terraform reports 'Error: Cycle'. What is a standard fix?

    Break the loop by creating the objects first and adding the cross-references as their own resources, such as security group rules.
  4. 4. In what order does Terraform destroy a subnet and the instance in it?

    Destroy follows the reversed graph: dependents are removed before the things they depend on.

Summary

  • References create implicit dependencies; prefer them whenever possible.
  • depends_on adds an explicit edge for hidden dependencies; use it rarely and comment why.
  • terraform graph prints the graph in DOT; arrows read "depends on".
  • Cycles are errors; break them by splitting resources.
  • Independent resources run in parallel; destroy reverses the order.
  • Use time_sleep for eventual consistency problems.

Next: count and for_each