Interview Prep/Real-World Interview/Write-Terraform tasks

Fix this Terraform that fails with "Cycle" or "Reference to undeclared resource".

IntermediateHands-onWrite-Terraform tasks
Answer

Broken:

resource "aws_security_group" "app" {
  ingress {
    from_port       = 5432
    to_port         = 5432
    protocol        = "tcp"
    security_groups = [aws_security_group.db.id]
  }
}
resource "aws_security_group" "db" {
  ingress {
    from_port       = 5432
    to_port         = 5432
    protocol        = "tcp"
    security_groups = [aws_security_group.app.id]
  }
}

Fixed: create both groups without inline rules, then add the rules as separate resources:

resource "aws_security_group" "app" {
  name   = "app"
  vpc_id = var.vpc_id
}

resource "aws_security_group" "db" {
  name   = "db"
  vpc_id = var.vpc_id
}

resource "aws_vpc_security_group_ingress_rule" "db_from_app" {
  security_group_id            = aws_security_group.db.id
  referenced_security_group_id = aws_security_group.app.id
  from_port                    = 5432
  to_port                      = 5432
  ip_protocol                  = "tcp"
}

Key trick → Two groups whose inline rules reference each other form a dependency cycle. Splitting the rules into separate resources breaks the cycle, because both groups now exist before either rule is created.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-Terraform tasks