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.
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.AdvancedCreate multiple IAM users from a list with `for_each`, and output their ARNs as a map.BeginnerWrite Terraform that looks up an existing VPC by tag instead of hardcoding its ID.Intermediate