Bỏ qua

1-Click Deployment

https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/create/review?templateURL=https://learn-cantrill-labs.s3.amazonaws.com/awscoursedemos/0021-aws-associate-ec2-instance-connect-vs-ssh/A4L_VPC_PUBLICINSTANCE_AL2023.yaml&stackName=EC2INSTANCECONNECTvsSSH

AWS IP Ranges https://ip-ranges.amazonaws.com/ip-ranges.json

🔐 EC2 Connection Methods: SSH vs Instance Connect (Demo thực hành)


🎯 Mục tiêu Demo

So sánh 2 cách connect EC2: 1. SSH Client (local machine) 2. EC2 Instance Connect (browser-based)


Chuẩn bị Infrastructure

1. Tạo Key Pair

EC2 Console  Key Pairs  Create Key Pair
Name: A4L
Format: .pem (Windows 10+/Mac/Linux) hoặc .ppk (Windows )
 Download file về máy

2. Deploy Infrastructure

CloudFormation One-click deployment:
Stack name: EC2-instance-connect-vs-SSH
Key name: A4L (auto-populated)
→ Wait for CREATE_COMPLETE

3. Kiểm tra Security Group

EC2 Instance → Security tab → Inbound rules:
- Port 80 (HTTP): 0.0.0.0/0
- Port 22 (SSH IPv4): 0.0.0.0/0  
- Port 22 (SSH IPv6): ::/0

Method 1: SSH Client (Local)

1. Connect Command

# AWS Console → Instance → Connect → SSH Client
# Copy command example:
ssh -i "A4L.pem" ec2-user@ec2-xx-xx-xx-xx.compute-1.amazonaws.com

2. Fix Permissions Error

# Lỗi thường gặp: "Permissions 0644 for 'A4L.pem' are too open"
chmod 400 A4L.pem

# Windows: Right-click file → Properties → Security → 
# Remove access for all users except current user

3. SSH Connection Process

# 1. Verify server fingerprint (type 'yes')
# 2. Authenticate with private key
# 3. Connected to EC2 instance terminal

Method 2: EC2 Instance Connect

1. Connect via Browser

EC2 Console → Instance → Connect → EC2 Instance Connect
Instance ID: auto-filled
Public IP: auto-filled
User name: ec2-user (auto-detected)
→ Click Connect

2. Key Differences vs SSH

✅ No key file needed
✅ Uses AWS IAM permissions
✅ Browser-based terminal
✅ Good for team access
❌ Requires specific IP ranges in Security Group

🔥 Critical Security Demo

Test 1: Restrict to "My IP"

1. Security Group → Edit Inbound Rules
2. SSH rule: Change 0.0.0.0/0 → My IP
3. Save rules

Results:
✅ SSH Client: Still works (from your IP)
❌ Instance Connect: Fails to connect

Test 2: Allow Instance Connect Service

1. Get AWS IP ranges: 
   https://ip-ranges.amazonaws.com/ip-ranges.json

2. Search for: "EC2_INSTANCE_CONNECT" + your region
   Example: "18.206.107.24/29" for us-east-1

3. Security Group: Add this IP range for SSH
4. Remove "My IP" rule

Results:
❌ SSH Client: Cannot connect
✅ Instance Connect: Works perfectly

Key Insights

SSH Client

How it works:
Your Machine → Internet → EC2 Instance

Requirements:
✅ Private key file (.pem)
✅ Correct file permissions (400)
✅ Security Group allows your IP
✅ Network connectivity

Pros/Cons:
✅ Direct connection
✅ Works from anywhere
❌ Key management overhead
❌ Each user needs key copy

Instance Connect

How it works:
Your Browser → AWS Service → EC2 Instance

Requirements:
✅ IAM permissions
✅ Security Group allows AWS service IPs
✅ Correct username

Pros/Cons:
✅ No key management
✅ IAM-based access control
✅ Audit trail in CloudTrail
❌ AWS service dependency
❌ Requires specific IP ranges

Production Best Practices

Security Group Strategy

🔒 Recommended approach:

Development:
- SSH from specific office IPs
- Instance Connect for team access

Production:
- Bastion hosts in public subnets
- Private instances via Session Manager
- No direct SSH from internet

Key Management

🔑 SSH Key best practices:

✅ One key per person/team
✅ Rotate keys regularly  
✅ Use AWS Systems Manager Session Manager
✅ Audit access with CloudTrail
❌ Don't share private keys
❌ Don't commit keys to code repos

Troubleshooting Common Issues

SSH Connection Failed

# Check these in order:
1. Key file permissions: chmod 400 key.pem
2. Security Group allows your IP
3. Instance is running
4. Correct username (ec2-user, ubuntu, admin)
5. Network connectivity

Instance Connect Failed

🐛 Common issues:
1. Security Group doesn't allow AWS service IPs
2. Wrong username (check AMI documentation)
3. No IAM permissions for EC2:SendSSHPublicKey
4. Instance not supported (very old AMIs)
EC2:SendSSHPublicKey-EC2 Instance Connect

là dịch vụ của AWS cho phép bạn kết nối SSH đến EC2 instance thông qua AWS Console hoặc CLI mà không cần quản lý SSH key truyền thống.

Cách hoạt động: - Khi bạn dùng Instance Connect, AWS sẽ tạm thời gửi một SSH public key lên EC2 instance - Permission EC2:SendSSHPublicKey cho phép user/role thực hiện action này - Key chỉ tồn tại trong thời gian ngắn (60 giây) để thiết lập kết nối SSH - Tại sao cần permission này? - Không có permission: User không thể gửi temporary SSH key lên instance - Kết quả: Instance Connect sẽ fail với lỗi authentication - Hoặc attach AWS managed policy: EC2InstanceConnectEndpoint

AMI username

Tại sao cần username? , để kết nối SSH, và username này phụ thuộc vào AMI (Amazon Machine Image) mà bạn sử dụng.

Khi dùng EC2 Instance Connect, AWS cần biết: - User nào trên EC2 instance để gửi temporary SSH key đến - Mỗi AMI có default user khác nhau

Username theo từng loại AMI:

AMI Type Default Username
Amazon Linux 2/2023 ec2-user
Ubuntu ubuntu
CentOS centos
RHEL (Red Hat) ec2-user hoặc root
SUSE ec2-user
Debian admin
Windows N/A (không dùng SSH)

Cách kiểm tra username đúng:

1. Trong AWS Console:

  • Vào EC2 → Instance → Select instance → Connect
  • Trong tab "EC2 Instance Connect", sẽ hiện Username field
  • AWS Console thường tự động đề xuất username phù hợp

2. Kiểm tra AMI documentation:

  • Vào EC2 → Instance → AMI ID → Xem description
  • Hoặc check documentation của AMI provider

3. Thử các username phổ biến:

  • ec2-user (phổ biến nhất)
  • ubuntu (nếu dùng Ubuntu)
  • admin (nếu dùng Debian)

Lỗi thường gặp:

Sai: Dùng root cho Amazon Linux
Đúng: Dùng ec2-user cho Amazon Linux

Sai: Dùng ec2-user cho Ubuntu
Đúng: Dùng ubuntu cho Ubuntu

Trong AWS CLI:

# Ví dụ connect với username đúng
aws ec2-instance-connect send-ssh-public-key \
    --instance-id i-1234567890abcdef0 \
    --instance-os-user ec2-user \  # Username ở đây
    --ssh-public-key file://my-key.pub

AWS Console Instance Connect thường tự động detect và fill username cho bạn rồi, nên thực tế ít khi phải lo lắng về việc này.

Tại sao vẫn có lỗi "Wrong username"?

Dù Console tự động suggest, nhưng vẫn có trường hợp:

1. Console detect sai:

  • AMI custom hoặc ít phổ biến
  • Console suggest ec2-user nhưng thực tế cần ubuntu hoặc ngược lại
  • AMI đã bị modify default user

2. User bị disable/không tồn tại:

  • Admin đã xóa hoặc disable default user
  • Instance được launch từ snapshot có user config khác

3. AMI quá cũ:

  • Một số AMI cũ không support Instance Connect
  • Thiếu ec2-instance-connect package

Khi nào cần quan tâm:

  • Console connect fail: Thử đổi username manually
  • Dùng CLI/API: Phải specify username chính xác
  • Custom AMI: Cần biết user nào được tạo

Thực tế:

  • 90% trường hợp: Console auto-detect đúng, không cần lo
  • 10% trường hợp: Phải manual check và sửa username

Exam Tips

Key Points to Remember

  • Instance Connect ≠ direct connection từ browser
  • Instance Connect cần AWS service IP ranges trong Security Group
  • SSH Client cần private key + đúng permissions
  • Security Group rules apply differently cho 2 methods

Common Questions

  1. "User can't connect via Instance Connect but SSH works" → Check Security Group for AWS service IPs
  2. "SSH permission denied" → Check file permissions (chmod 400)
  3. "Best practice for team access" → Instance Connect với IAM permissions
  4. "Production security" → Use Session Manager, not direct SSH

Clean Up

CloudFormation  Delete stack "EC2-instance-connect-vs-SSH"

Takeaway: Instance Connect tốt cho team access với IAM control, SSH Client tốt cho individual access. Production nên dùng Session Manager thay vì expose SSH ra internet!