Managing multiple AWS EC2 instances efficiently can be challenging, especially when dealing with different SSH keys, IP addresses, and user configurations. This guide will show you how to streamline your SSH workflow using the SSH config file, SSH agent, and tmux for better productivity.
Using SSH config file
Instead of typing long SSH commands with IP addresses and keys every time, we can define SSH configurations ~/.ssh/config
Step 1: Open the SSH config file
Run the following command. If the file does not exist, create it.
1
nano ~/.ssh/config
Step 2: Add multiple EC2 instances
Define each instance in the config file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Production Instance
Host ec2-production
HostName 44.204.XXX.XXX # Replace with actual IP
User ubuntu
IdentityFile ~/.ssh/my-prod-key.pem
# Staging Instance
Host ec2-staging
HostName 44.216.XXX.XXX
User ubuntu
IdentityFile ~/.ssh/my-staging-key.pem
# Development Instance
Host ec2-dev
HostName 44.14.XXX.XXX
User ubuntu
IdentityFile ~/.ssh/my-dev-key.pem
Step 3: Set correct permissions
1
chmod 600 ~/.ssh/config
Step 4: Connect easily
1
2
3
ssh ec2-production
ssh ec2-staging
ssh ec2-dev
Using SSH agent for key management
If you have multiple private keys (.pem files), managing them manually can be tedious. The SSH agent allows you to store keys in memory for seamless authentication.
Step 1: Start SSH agent
Run the following command
1
eval "$(ssh-agent -s)"
Step 2: Add SSH keys
Add your keys to the SSH agent.
1
2
3
ssh-add ~/.ssh/my-prod-key.pem
ssh-add ~/.ssh/my-staging-key.pem
ssh-add ~/.ssh/my-dev-key.pem
Automating SSH sessions with Tmux
If you frequently switch between multiple EC2 instances, using tmux can make managing multiple SSH sessions easier.
Step 1: Install tmux
1
sudo apt install tmux -y
Step 2: Create persistent SSH sessions
You can create multiple SSH sessions and switch between them easily
1
2
3
tmux new-session -s prod -d "ssh ec2-production"
tmux new-session -s staging -d "ssh ec2-staging"
tmux new-session -s dev -d "ssh ec2-dev"
Step 2: Switch between sessions
To attach to a session.
1
tmux attach -t prod
To detach from a session, press Ctrl + B, then D.
By implementing these techniques:
SSH Config file ==> Simplifies connection management with aliases.
SSH Agent ==> Eliminates repeated authentication for multiple keys.
Tmux ==> Efficiently manages multiple SSH sessions.
These methods significantly enhance productivity and streamline AWS EC2 access. If you manage multiple instances, adopting these best practices will save time and effort.