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.
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.idCommon 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.
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
- Run
terraform graphto see the dependency edges forming the cycle. - Remove any unnecessary
depends_onthat closes the loop. - 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_onsparingly and only for true ordering needs. - Inspect
terraform graphwhen introducing cross-resource references.