Narcis Neacsu
Narcis Neacsu

Reputation: 1193

I get the "Failed to connect to the host via ssh" error when Ansible tries to connect to a machine via ssh using private key

I am trying to provision a machine using ansible. I must connect to it via ssh using a private key, instead of password.

This is the content of my inventory.txt file:

target ansible_host=<ip_address> ansible_ssh_private_key_file=~/.ssh/<private_key_name>.pem

This is the content of my playbook.yaml file:

-
  name: Playbook name
  hosts: target
  tasks:
   <task_list>

When I am executing the command ansible-playbook <playbook_name>.yaml -i inventory.txt I get the following error:

fatal: [target]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Permission denied (publickey).\r\n", "unreachable": true}

I also tried executing the following command: ansible-playbook <playbook_name>.yaml --private-key=~/.ssh/<private_key_name>.pem -i inventory.txt, without the ansible_ssh_private_key_file property inside the inventory.txt file.

Note: I can connect to the machine using the command ssh -i <private_key_name>.pem <username>@<ip_address>.

How can I resolve this issue ?

Upvotes: 1

Views: 4546

Answers (1)

Szczad
Szczad

Reputation: 836

I suspect you are connecting as different user. In the above example you use <user>@<host> during ssh checks but you don't have ansible_user=... field configured. Try providing username this way in hosts file.

Upvotes: 2

Related Questions