You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Security and networking are fundamental to running EC2 instances. This lesson covers the three pillars you configure for every instance: key pairs for authentication, security groups for firewall rules, and VPC networking for connectivity.
EC2 uses asymmetric cryptography (public/private key pairs) to control access to instances.
.pem file).# Create a key pair
aws ec2 create-key-pair \
--key-name my-app-key \
--key-type ed25519 \
--query "KeyMaterial" \
--output text > my-app-key.pem
chmod 400 my-app-key.pem
| Type | Description |
|---|---|
| RSA | Traditional; widely supported; 2048-bit or 4096-bit |
| ED25519 | Modern; smaller keys; faster authentication; recommended for new instances |
~/.ssh/authorized_keys file on instances.EC2 Instance Connect pushes a temporary SSH key to the instance metadata for 60 seconds. You do not need to manage long-lived key pairs:
# Push a temporary key and connect
aws ec2-instance-connect send-ssh-public-key \
--instance-id i-0123456789abcdef0 \
--instance-os-user ec2-user \
--ssh-public-key file://my-temporary-key.pub
# Then SSH as usual
ssh -i my-temporary-key ec2-user@<public-ip>
Session Manager provides a browser-based or CLI shell without any SSH key or open inbound port:
# Start a session (requires SSM Agent on the instance and appropriate IAM role)
aws ssm start-session --target i-0123456789abcdef0
Advantages: no open inbound ports, all sessions are logged to CloudTrail, supports IAM-based access control.
A security group is a stateful virtual firewall that controls traffic to and from one or more EC2 instances. "Stateful" means that if you allow inbound traffic, the corresponding outbound response is automatically allowed (and vice versa).
| Direction | Default Rule |
|---|---|
| Inbound | All traffic denied (no rules = no access) |
| Outbound | All traffic allowed (default rule permits all outbound) |
Each rule specifies:
| Field | Description | Example |
|---|---|---|
| Type | Protocol / service | SSH, HTTP, Custom TCP |
| Protocol | TCP, UDP, ICMP, or All | TCP |
| Port range | Single port or range | 22, 443, 8080-8090 |
| Source / Destination | IP range (CIDR), security group ID, or prefix list | 10.0.0.0/16, sg-0abc123 |
Web Server Security Group:
Inbound:
HTTP (TCP 80) from 0.0.0.0/0
HTTPS (TCP 443) from 0.0.0.0/0
SSH (TCP 22) from 203.0.113.0/24 (your office IP)
Outbound:
All traffic to 0.0.0.0/0
Database Security Group:
Inbound:
MySQL (TCP 3306) from sg-web-server (reference by SG ID)
Outbound:
All traffic to 0.0.0.0/0
Key insight: Referencing another security group as the source (e.g.,
sg-web-server) is more secure than using IP addresses. It automatically adapts when instances are added or removed.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.