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

Write a security group that allows HTTPS from anywhere and SSH only from an office CIDR.

BeginnerHands-onWrite-Terraform tasks
Answer
resource "aws_security_group" "web" {
  name   = "web"
  vpc_id = aws_vpc.main.id
}

resource "aws_vpc_security_group_ingress_rule" "https" {
  security_group_id = aws_security_group.web.id
  cidr_ipv4         = "0.0.0.0/0"
  from_port         = 443
  to_port           = 443
  ip_protocol       = "tcp"
}

resource "aws_vpc_security_group_ingress_rule" "ssh_office" {
  security_group_id = aws_security_group.web.id
  cidr_ipv4         = var.office_cidr
  from_port         = 22
  to_port           = 22
  ip_protocol       = "tcp"
}

resource "aws_vpc_security_group_egress_rule" "all" {
  security_group_id = aws_security_group.web.id
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "-1"
}

Key trick → The per-rule resources are the current recommendation. Mixing inline ingress blocks with separate rule resources makes them fight on every apply. Terraform removes AWS's default allow-all egress, so you must declare egress yourself.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-Terraform tasks