Security Groups and Key Pairs
Control inbound and outbound traffic with security groups and manage SSH authentication with EC2 key pairs.
What Are Security Groups?
A security group is a virtual stateful firewall that controls inbound and outbound traffic to and from an EC2 instance (or other AWS resources like RDS, Lambda, ELB). Security groups operate at the instance level—each rule specifies a protocol (TCP/UDP/ICMP), port range, and source/destination (IP range or another security group). Unlike traditional firewalls, security groups are stateful: if you allow inbound traffic, the response traffic is automatically allowed outbound without an explicit rule.
Inbound and Outbound Rules
Security groups have separate inbound and outbound rule sets. Inbound rules control traffic arriving at the instance—by default, all inbound traffic is denied. Outbound rules control traffic leaving the instance—by default, all outbound traffic is allowed. You add explicit Allow rules; there are no explicit Deny rules in security groups (use Network ACLs for explicit denies). All rules in a security group are evaluated together using a logical OR—any matching Allow rule permits the traffic.
# Add an inbound SSH rule to a security group
aws ec2 authorize-security-group-ingress \
--group-id sg-12345678 \
--protocol tcp \
--port 22 \
--cidr 203.0.113.0/24
# Add an inbound HTTP rule
aws ec2 authorize-security-group-ingress \
--group-id sg-12345678 \
--protocol tcp \
--port 80 \
--cidr 0.0.0.0/0All lessons in this course
- Launching Your First EC2 Instance
- Instance Types and Pricing Models
- Security Groups and Key Pairs
- EC2 Storage: Instance Store vs EBS