DEV Community

Ajit Kumar
Ajit Kumar

Posted on

Note: SSH to EC2 without specifying .pem

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

  1. 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
Enter fullscreen mode Exit fullscreen mode
  1. Edit or Create the SSH Configuration File Open or create the SSH configuration file at ~/.ssh/config:
   nano ~/.ssh/config
Enter fullscreen mode Exit fullscreen mode
  1. 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
Enter fullscreen mode Exit fullscreen mode

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.
  1. Save and Exit
    Save the file and exit the editor (for Nano, press CTRL+O, Enter, then CTRL+X).

  2. Test the Configuration
    Use the alias to connect without specifying the .pem file:

   ssh your-ec2-alias
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

After this setup, you won't need to specify the .pem file manually every time.

Top comments (0)