To avoid specifying .pem
A key file is created each time you connect to an EC2 instance. You can configure the SSH client to automatically use this key by editing the SSH configuration file.
Steps to set up SSH to automatically use keys
-
find your
.pem
document
Make sure your private key (.pem
files) are stored securely and have the correct permissions:
chmod 400 /path/to/your-key.pem
-
Edit or create an SSH profile
Open or create an SSH profile~/.ssh/config
:
nano ~/.ssh/config
-
Perform individual new configurations for your EC2
Add an entry for your EC2 instance to the file:
Host your-ec2-alias
HostName
User ec2-user
IdentityFile /path/to/your-key.pem
replace:
-
your-ec2-alias
Give your instance a nickname (for example,my-ec2
). -
The public IP or hostname of the individual instance associated with your EC2 execution.
-
/path/to/your-key.pem
and your full path.pem
document.
-
Save and exit
Save the file and exit the editor (for Nano, pressCTRL+O
,Enter
ThenCTRL+X
). -
Test configuration
Connect using alias without specifying.pem
document:
ssh your-ec2-alias
Example: SSH configuration file
If you have multiple instances, your ~/.ssh/config
The file might look like this:
Host my-first-ec2
HostName 192.0.2.1
User ec2-user
IdentityFile /home/username/.ssh/first-key.pem
Host my-second-ec2
HostName 203.0.113.2
User ec2-user
IdentityFile /home/username/.ssh/second-key.pem
Extra tips
- Add a new default key: If most of your EC2 instances use the same key, you can set a global default:
Host *
IdentityFile /path/to/default-key.pem
-
Avoid permission issues: make sure
.pem
files and~/.ssh/config
The file can only be read by your user:
chmod 600 ~/.ssh/config
chmod 400 /path/to/your-key.pem
After completing this setup, you will not need to specify .pem
File manually every time.