To avoid specifying the .pem
file every time you connect to an EC2 instance, you can configure your SSH client to use the key automatically by editing your SSH configuration file.
Steps to Set Up SSH for Automatic Key Usage
-
Locate Your
.pem
File Make sure your private key (.pem
file) is stored securely and has the correct permissions:
chmod 400 /path/to/your-key.pem
-
Edit or Create the SSH Configuration File
Open or create the SSH configuration file at
~/.ssh/config
:
nano ~/.ssh/config
- Add Configuration for Your EC2 Instance Add an entry for your EC2 instance to the file:
Host your-ec2-alias
HostName <instance-public-ip-or-hostname>
User ec2-user
IdentityFile /path/to/your-key.pem
Replace:
-
your-ec2-alias
with a nickname for your instance (e.g.,my-ec2
). -
<instance-public-ip-or-hostname>
with the public IP or hostname of your EC2 instance. -
/path/to/your-key.pem
with the full path to your.pem
file.
Save and Exit
Save the file and exit the editor (for Nano, pressCTRL+O
,Enter
, thenCTRL+X
).Test the Configuration
Use the alias to connect without specifying the.pem
file:
ssh your-ec2-alias
Example: SSH Config File
If you have multiple instances, your ~/.ssh/config
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
Additional Tips
- Add a 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 Permissions Issues: Ensure the
.pem
file and the~/.ssh/config
file are readable only by your user:
chmod 600 ~/.ssh/config
chmod 400 /path/to/your-key.pem
After this setup, you won't need to specify the .pem
file manually every time.
Top comments (0)