How to fix Ansible failed to connect to remote machine due to publickey,password

Sometimes you will encounter an issue when connect to remote machine using Ansible, an example error is shown below:

[vagrant@localhost playbooks]$ ansible testserver -i hosts -m ping
testserver | UNREACHABLE! => {
“changed”: false,
“msg”: “Failed to connect to the host via ssh: Permission denied (publickey,password).\r\n”,
“unreachable”: true
}

The reason is you didn’t set up your private/public key properly, for example, if you try ssh username@remotehost, it will ask you for password, to fix it, follow the steps below (from: https://www.howtogeek.com/tips/bypass-ssh-logins-by-adding-your-key-to-a-remote-server-in-a-single-command/)

If you want to setup SSH keys to allow logging in without a password, you can do so with a single command. It’s quite easy.

The first thing you’ll need to do is make sure you’ve run the keygen command to generate the keys (if you have already generated keys, skip this step).

ssh-keygen -t rsa

Then use this command to push the key to the remote server, modifying it to match your server user name and host name.

cat ~/.ssh/id_rsa.pub | ssh user@hostname 'cat >> .ssh/authorized_keys'

You’ll have to enter your password the first time to copy the keys. After that, you should be able to login without a password, or even use scp or rsync without entering a password. You can test with this command:

ssh user@hostname

It’s definitely a lot easier than typing in a password all the time.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s