Note: SSH to EC2 without specifying .pem
December 23, 2024

Note: SSH to EC2 without specifying .pem

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

  1. 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
Enter full screen mode

Exit full screen mode

  1. Edit or create an SSH profile
    Open or create an SSH profile ~/.ssh/config:
   nano ~/.ssh/config
Enter full screen mode

Exit full screen mode

  1. 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
Enter full screen mode

Exit full screen mode

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

  2. Test configuration
    Connect using alias without specifying .pem document:

   ssh your-ec2-alias
Enter full screen mode

Exit full screen mode




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
Enter full screen mode

Exit full screen mode




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
Enter full screen mode

Exit full screen mode

  • 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
Enter full screen mode

Exit full screen mode

After completing this setup, you will not need to specify .pem File manually every time.

2024-12-23 01:44:11

Leave a Reply

Your email address will not be published. Required fields are marked *