Logo

Terraform For Security Groups

In AWS a security group is like a firewall. Here we want to set up a firewall for our EC2 web server. Four things should be allowed:

  1. I need to be able to SSH into the server
  2. HTTP traffic needs to be allowed
  3. HTTPS traffic needs to be allowed
  4. All outbound traffic needs to be allowed to allow for downloading of updates

Nothing special here. Still, when I was first learning Terraform and AWS such examples were helpful.

data "aws_vpc" "selected" {
  default = true
}

resource "aws_security_group" "webserver_rules" {
  name        = "webserver rules"
  description = "Allow SSH, HTTP, HTTPS"
  vpc_id      = data.aws_vpc.selected.id
}

resource "aws_security_group_rule" "https" {
  type              = "ingress"
  from_port         = 443
  to_port           = 443
  protocol          = "tcp"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = aws_security_group.webserver_rules.id
}

resource "aws_security_group_rule" "http" {
  type              = "ingress"
  from_port         = 80
  to_port           = 80
  protocol          = "tcp"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = aws_security_group.webserver_rules.id
}

resource "aws_security_group_rule" "ssh" {
  type              = "ingress"
  from_port         = 22
  to_port           = 22
  protocol          = "tcp"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = aws_security_group.webserver_rules.id
}

resource "aws_security_group_rule" "outbound" {
  type              = "egress"
  from_port         = 0
  to_port           = 65535
  protocol          = "tcp"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = aws_security_group.webserver_rules.id
}