Unable to connect to the AWS EC2 instance - "Host key verification failed"

Solution 1:

When you connect to a ssh server your ssh client keeps a list of trusted hosts as key-value pairs of IP and ssh server finger print. With ec2 you often reuse the same IP with several server instances which causes conflict.

If you have connected to an earlier ec2 instance with this IP, and now connect to a new instance with the same IP your computer will complain of "Host verification failed" as its previously stored pair no longer matches the new pair.

The error message tells you how to fix it:

Offending RSA key in /home/ubuntu/.ssh/known_hosts:1
remove with: ssh-keygen -f "/home/ubuntu/.ssh/known_hosts" -R 46.137.253.231"

Alternative simply open /home/ubuntu/.ssh/known_hosts and delete line 1 (as indicated by the ":1").

You can now connect and receive a new host verification.

Please note usually ssh's known_hosts file usually have stored a second line pair for hostname or ip6 value so you might need to remove a couple of lines.

Warning: Host verification is important and it is a good reason why you get this warning. Make sure you are expecting host verification to fail. Do not remove the verification key-value pair if not certain.

Solution 2:

@flurdy's answer is good as a one-off resolution.

But if you often:

  • launch new EC2 instances,
  • start and stop EC2 instances,

..without using Elastic IPs (permanently attached to your servers) then you deal with new/changing IPs/hostnames of your instances all the time.

If so then you may want to permanently stop SSH checking and storing server fingerprints for EC2 public hostnames.


To do that just add this to your ~/.ssh/config:

# AWS EC2 public hostnames (changing IPs)
Host *.compute.amazonaws.com 
  StrictHostKeyChecking no
  UserKnownHostsFile /dev/null


Please note that SSH will still say Warning: Permanently added (...) to the list of known hosts. when connecting but just means that it has added it to /dev/null...

SSH will however stop asking if you confirm the authenticity of host and just continue connecting.

So it is more convenient and you may avoid not always verbose enough SSH connection errors while using your EC2 instances.


I have to add that in theory this setting lowers security of your SSH connections but in the real life you probably wouldn't check the fingerprints of your one-off EC2 instances anyway.