terraform dependency_error ai_generated partial

Error: Cycle

ID: terraform/cycle-in-module

Also available as: JSON · Markdown
55%Fix Rate
78%Confidence
75Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

Circular dependency between resources. Terraform cannot determine apply order.

generic

Workarounds

  1. 78% success Use terraform graph to visualize the cycle and refactor
    terraform graph | dot -Tpng > graph.png

    Sources: https://developer.hashicorp.com/terraform/cli/commands/graph

  2. 72% success Break the cycle by using data sources instead of direct references for one direction
    # Instead of direct reference creating a cycle:
    # resource "aws_security_group" "a" { ... references sg_b }
    # resource "aws_security_group" "b" { ... references sg_a }
    
    # Break one direction with a data source:
    resource "aws_security_group" "a" {
      name = "sg-a"
    }
    data "aws_security_group" "a_lookup" {
      name = "sg-a"
      depends_on = [aws_security_group.a]
    }
    resource "aws_security_group" "b" {
      ingress {
        security_groups = [data.aws_security_group.a_lookup.id]
      }
    }

    Sources: https://developer.hashicorp.com/terraform/language/data-sources

Dead Ends

Common approaches that don't work:

  1. Add depends_on to break the cycle 65% fail

    depends_on can make cycles worse by adding more edges to the dependency graph

  2. Move resources to separate modules 60% fail

    Cycles across modules are even harder to debug

Error Chain

Leads to:
Preceded by: