Table of Contents
The Error
Error: Cycle: aws_security_group.a, aws_security_group.b
What Causes This
Terraform builds a dependency graph to determine resource creation order. A cycle occurs when Resource A depends on Resource B, which depends on Resource A — creating an infinite loop. This commonly happens with security group rules, IAM policies referencing each other, or modules with circular outputs.
How to Fix It
Solution 1: Break the Cycle with Separate Rules
# BAD — creates a cycle
resource "aws_security_group" "a" {
ingress {
security_groups = [aws_security_group.b.id]
}
}
resource "aws_security_group" "b" {
ingress {
security_groups = [aws_security_group.a.id]
}
}
# GOOD — use separate rule resources
resource "aws_security_group" "a" {
name = "sg-a"
}
resource "aws_security_group" "b" {
name = "sg-b"
}
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
from_port = 443
to_port = 443
protocol = "tcp"
}
resource "aws_security_group_rule" "b_from_a" {
type = "ingress"
security_group_id = aws_security_group.b.id
source_security_group_id = aws_security_group.a.id
from_port = 443
to_port = 443
protocol = "tcp"
}
Solution 2: Visualize the Graph
terraform graph | dot -Tsvg > graph.svg
# Look for cycles in the visualization
Solution 3: Use depends_on Carefully
Avoid unnecessary depends_on — it creates explicit dependencies that can cause cycles. Let Terraform infer dependencies from resource references instead.
Prevention Tips
- Pin provider versions — avoid surprise breaking changes
- Use CI/CD — catch errors before they hit production
- Test with
terraform plan— always review before applying - Keep Terraform updated — newer versions have better error messages
- Use
terraform validate— catches syntax errors early
Hands-On Courses
Learn to avoid these errors with interactive, project-based courses:
- Terraform for Beginners on CopyPasteLearn
- Terraform By Example — practical code examples
- Terraform Cheat Sheet — quick reference for all commands
Related Articles
- Terraform Troubleshooting - Common Errors and Solutions
- Terraform Enabling and Using Debugging
- Debugging with TFLint
Conclusion
This error is common and fixable. Follow the solutions above, and check our Terraform course for hands-on training that covers real-world troubleshooting scenarios.

