Loading

Quipoin Menu

Learn • Practice • Grow

terraform / Security Groups
tutorial

Security Groups

Security groups act as virtual firewalls for your EC2 instances. In this chapter, we'll create a security group that allows HTTP and SSH traffic and attach it to our instance.

Creating a Security Group

Add the following resource to your main.tf:
resource "aws_security_group" "web_sg" {
name = "web-sg"
description = "Allow HTTP and SSH"

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

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

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

tags = {
Name = "web-sg"
}
}

Attaching Security Group to EC2 Instance

Modify the aws_instance resource to reference the security group:
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
key_name = aws_key_pair.deployer.key_name
vpc_security_group_ids = [aws_security_group.web_sg.id]
user_data = file("user_data.sh")

tags = { Name = "terraform-web" }
}

Using Variables for Security Group Rules

To make it reusable, define variables:
variable "allowed_ssh_cidrs" {
type = list(string)
default = ["0.0.0.0/0"]
}

resource "aws_security_group" "web_sg" {
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = var.allowed_ssh_cidrs
}
}

Security Group Outputs

Expose the security group ID for other modules:
output "web_sg_id" {
value = aws_security_group.web_sg.id
}


Two Minute Drill
  • Security groups control inbound and outbound traffic.
  • Define ingress and egress rules with ports and CIDR blocks.
  • Attach to EC2 instance using vpc_security_group_ids.
  • Use variables to make CIDR blocks configurable.

Need more clarification?

Drop us an email at career@quipoinfotech.com