AWS SSH Permission denied (PublicKey) Error [Solved]

avatar
Borislav Hadzhiev

Last updated: Feb 26, 2024
2 min

banner

# AWS SSH Permission denied (PublicKey) Error [Solved]

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 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 the 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 to 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 as follows:

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

Once I updated the username to 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.

I've also written a detailed guide on how to provision and configure an EC2 instance in AWS CDK.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.