Skip to content
Latchkey

OpenTofu "Cycle" dependency error in CI

OpenTofu builds a dependency graph and could not produce an order because two or more nodes reference each other in a loop. It prints "Error: Cycle" with the chain of resources involved.

What this error means

tofu plan or apply fails with "Error: Cycle:" followed by a list of resources that reference one another, so no valid apply order exists.

tofu
Error: Cycle: aws_security_group.a, aws_security_group.b

Two or more resources depend on each other, so OpenTofu cannot determine a
valid order in which to create or update them.

Common causes

Mutual references between resources

Resource A references B and B references A (common with security groups referencing each other), forming a cycle.

A module output that loops back into its input

A value flows out of a module and back into something the module depends on, closing a loop across the boundary.

How to fix it

Break the loop with a separate association

  1. Identify the two resources in the cycle from the error.
  2. Remove the direct cross-reference and use a standalone association resource.
  3. Re-run plan to confirm the graph now orders.
main.tf
resource "aws_security_group_rule" "a_to_b" {
  security_group_id        = aws_security_group.a.id
  source_security_group_id = aws_security_group.b.id
  type                     = "ingress"
}

Inspect the graph to locate the loop

Render the dependency graph to see exactly which edges close the cycle.

Terminal
tofu graph | grep -i cycle
tofu graph > graph.dot

How to prevent it

  • Avoid mutual references; use standalone association resources.
  • Keep module inputs and outputs acyclic across boundaries.
  • Review tofu graph when adding cross-resource references.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →