Create a Security Group on AWS with Terraform

This AWS and Terraform blog post will show how to create a security group using a Terraform configuration code.

Security Groups

AWS Security Groups are virtual firewalls that we use to protect AWS EC2 instances. The security group has a list of all the allowed inbound and outbound ports.

Ingress and Egress

Terraform terminology uses Ingress traffic as inbound and Egress as outbound.

Configuration

In the following Terraform configuration, I create a Security Group that allows two incoming ports from everywhere. The ports are 3389 and 22. By default, all outbound traffic is allowed using egress.

terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = "3.47.0"
    }
  }
}

provider "aws" {
  region = "us-west-2"
}

resource "aws_security_group" "sg" {
  name = "My AWS SG"
  description = "Terraform created SG"

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

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

  egress {
    from_port        = 0
    to_port          = 0
    protocol         = "-1"
    cidr_blocks      = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]
  }
 
 tags = {
    Name = "My security group"
  }
}

Leave a comment

Your email address will not be published. Required fields are marked *