Solve - AWS SSH Permission denied (PublicKey) Error

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Solving AWS SSH Permission denied (PublicKey) Error #

There are 2 main reasons the "Permission denied (publickey)" error occurs when trying to SSH into an AWS EC2 instance:

  1. The username in the ssh connection URL is incorrect. The username is different for the different Amazon Machine Images.
  2. The permissions of the private key are incorrect.

permission denied publickey

To solve the "Permission denied (publickey)" error when trying to SSH into an EC2 instance:

  1. Open your terminal in the directory where your private key is located and change its permissions to only be readable by the current user.
shell
chmod 600 ec2-private-key.pem
  1. In the AWS EC2 console, click on checkbox next to your instance's name, then click on Actions and select Connect. Click on the SSH client tab and copy the ssh command example.

ssh command example

The example above uses an Amazon Linux AMI, therefore the username isec2-user. However, the connection string in the console is not always correct. If you are launching an ubuntu instance, the username will be ubuntu, for bitnami instances it is bitnami.

An easy way for find the username for your AMI is to try to log in as root and read the error message:

shell
ssh -i "ec2-private-key.pem" root@YOUR_EC2_PUBLIC_DNS

try login as root

The error message shows the username we should specify to SSH into the EC2 instance - in this case ec2-user.

Therefore our SSH command should look like:

shell
ssh -i "ec2-private-key.pem" ec2-user@YOUR_EC2_PUBLIC_DNS

Once I updated the username to be ec2-user, the connection was established successfully:

corrected username

If you are still getting the error after correcting the username, run the ssh command in verbose mode:

shell
ssh -v -i "ec2-private-key.pem" ec2-user@YOUR_EC2_PUBLIC_DNS

The -v flag, stands for verbose and logs the ssh command's output to the terminal. The flag is very helpful for debugging.

Make sure to open your terminal in the directory where your ec2-private-key.pem file is located. Otherwise, you might get a permission denied error because the file could not be found.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.