1. Security Group
A virtual firewall that controls inbound and outbound traffic. It acts as a filter for traffic to and from the instances in a VPC.
-> which traffic is allowed to reach some instances based on the source and destination.
It is private subnet. Why Security Group is needed?
-vs route table
Route Table is used to control the routing of network traffic within a VPC. (subnet - internet). But SG is about instance.
resource "aws_security_group" "ec2_sg_private" {
description = "security group for ec2"
vpc_id = var.vpc_id
ingress {
description = "allow ssh"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["10.0.0.0/8"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "ec2-sg"
}
}
The ingress block defines the inbound rules for the security group. In this case, the security group allows inbound TCP traffic on only 22 port from any IP address within the VPC CIDR range of 10.0.0.0/8.
This means that any resource within the same VPC as the security group can initiate a TCP connection to an EC2 instance associated with this security group.
(TODO: check the private subnet case)
The egress block defines the outbound rules for the security group. In this case, the security group allows all outbound traffic (protocol "-1") to any destination IP address (CIDR block 0.0.0.0/0). This means that any resource associated with this security group can send traffic to any destination on any protocol.
2. EC2 instance
resource "aws_instance" "ec2" {
ami = var.ami
instance_type = var.instance_type
vpc_security_group_ids = [aws_security_group.ec2_sg_private.id]
associate_public_ip_address = var.associate_public_ip_address
subnet_id = var.subnet_id
tags = {
Name = var.name
}
}
Ec2 itself has simple config.
We have to specify the connection btw sg and vpc.
Just vpc_security_group_ids doesn bake the connection btw them.