Skip to content
Latchkey

Terraform "Cycle" - Fix Dependency Cycles in CI

Terraform builds a dependency graph and must order resources so each is created after what it depends on. A cycle - A depends on B and B depends on A - has no valid order, so Terraform refuses to plan.

What this error means

A command fails with Error: Cycle: followed by the chain of resources that reference each other. There is no transient cause - it is a structural problem in how the resources depend on one another.

terraform output
Error: Cycle: aws_security_group.a, aws_security_group.b

  aws_security_group.a references aws_security_group.b.id
  aws_security_group.b references aws_security_group.a.id

Common causes

Resources reference each other directly

Two resources each use the other’s attributes (e.g. two security groups referencing each other’s IDs in rules), forming a loop with no valid creation order.

A misplaced depends_on

An explicit depends_on that points back into a resource’s own dependency chain can introduce a cycle the implicit graph would not have.

How to fix it

Break the cycle with standalone rules

Move the mutual references out of the resources into separate rule resources so each group is created first, then linked.

main.tf
resource "aws_security_group" "a" {}
resource "aws_security_group" "b" {}

resource "aws_security_group_rule" "a_to_b" {
  type                     = "ingress"
  security_group_id        = aws_security_group.a.id
  source_security_group_id = aws_security_group.b.id
}

Visualize and remove the loop

  1. Run terraform graph to see the dependency edges forming the cycle.
  2. Remove any unnecessary depends_on that closes the loop.
  3. Introduce an intermediate resource so the two sides no longer reference each other directly.

How to prevent it

  • Use standalone rule/association resources instead of mutual references.
  • Add depends_on sparingly and only for true ordering needs.
  • Inspect terraform graph when introducing cross-resource references.

Related guides

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