Skip to content

Security Groups

Security groups are used to handle Firewall rules or any other type of access management in AWS.

This exercise will create two security group resource type of blocks. You learn how to combine variables and strings together and how to call/use data blocks in Terraform.

Security Group for Load Balancer

  1. Create a resource block with type aws_security_group and name it alb with following parameters:
    1. name = "${var.service_name}-alb" . This is how you can combine string with a variable.
    2. description = Access to ALB
    3. vpc_id = var.vpc_id OR data.aws_vpc.this.id
    4. Firewall rules:
      ingress {
          protocol    = "tcp"
          from_port   = 80
          to_port     = 80
          cidr_blocks = ["0.0.0.0/0"]
      }
      
      egress {
          from_port = 0
          to_port   = 0
          protocol  = "-1"
          cidr_blocks = ["0.0.0.0/0"]
      }
      

Security Group for ECS

  1. Create a variable block with name frontend_port to your variables.tf file with following params:
    1. type = number
    2. default = 80
  2. Create a resource block with type aws_security_group and name it ecs with following parameters:
    1. name = "${var.service_name}-ecs"
    2. description = allow only inbound access from the ALB
    3. vpc_id = var.vpc_id
    4. Firewall rules:
      ingress {
          protocol        = "tcp"
          from_port       = var.frontend_port
          to_port         = var.frontend_port
          security_groups = [aws_security_group.alb.id]
      }
      
      egress {
          protocol    = "-1"
          from_port   = 0
          to_port     = 0
          cidr_blocks = ["0.0.0.0/0"]
      }
      

Check your configuration

To check your Terraform configuration run

terraform plan

It will show you the resources that Terraform will create,delete or change. It will not apply anything.


Answer

terraform/security_groups.tf

resource "aws_security_group" "alb" {
  name        = "${var.service_name}-alb"
  description = "Access to ALB"
  vpc_id      = var.vpc_id

  ingress {
    protocol    = "tcp"
    from_port   = 80
    to_port     = 80
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port = 0
    to_port   = 0
    protocol  = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_security_group" "ecs" {
  name        = "${var.service_name}-ecs"
  description = "allow inbound access from the ALB only"
  vpc_id      = var.vpc_id

  ingress {
    protocol        = "tcp"
    from_port       = var.frontend_port
    to_port         = var.frontend_port
    security_groups = [aws_security_group.alb.id]
  }

  egress {
    protocol    = "-1"
    from_port   = 0
    to_port     = 0
    cidr_blocks = ["0.0.0.0/0"]
  }
}