Skip to content
Latchkey

Terraform "Cycle" dependency error in CI

Terraform builds a directed acyclic graph of dependencies to order operations. When references form a loop, no valid order exists, so Terraform stops with "Error: Cycle" and lists the nodes in the loop.

What this error means

plan or apply fails with "Error: Cycle:" followed by a chain of resource addresses that reference each other.

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

Common causes

Two resources reference each other directly

Each resource uses an attribute of the other (for example two security groups referencing each other), so neither can be created first.

A depends_on creates a back edge

An explicit depends_on, combined with an attribute reference in the other direction, closes a loop in the graph.

How to fix it

Break the loop with a separate rule resource

For mutually referencing security groups, move the cross-references into standalone rule resources so the groups no longer depend on each other.

main.tf
resource "aws_security_group_rule" "a_from_b" {
  type                     = "ingress"
  security_group_id        = aws_security_group.a.id
  source_security_group_id = aws_security_group.b.id
  # ...
}

Inspect the graph to find the loop

Render the dependency graph to see exactly which edges form the cycle, then remove the unnecessary reference.

Terminal
terraform graph | grep -i cycle

How to prevent it

  • Split mutual references into separate rule or association resources.
  • Avoid depends_on that points back into a resource you also reference.
  • Keep module interfaces one-directional to avoid graph loops.

Frequently asked questions

What causes ""Error: Cycle""?
Each resource uses an attribute of the other (for example two security groups referencing each other), so neither can be created first.
How do I fix "Error: Cycle"?
For mutually referencing security groups, move the cross-references into standalone rule resources so the groups no longer depend on each other.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card