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.
More on Write-Terraform tasks
Write Terraform for an S3 bucket with versioning, encryption and public access blocked.BeginnerWrite the remote backend configuration with S3 and state locking.BeginnerWrite a VPC with public and private subnets across 3 AZs using `count` or `for_each`.IntermediateWrite a reusable module for an EC2 instance with inputs, outputs and validation.AdvancedWrite a security group that allows HTTPS from anywhere and SSH only from an office CIDR.BeginnerCreate multiple IAM users from a list with `for_each`, and output their ARNs as a map.Beginner