Search code examples
sshansibleansible-inventoryansible-ad-hoc

Ansible Permission denied (public key) but ssh using same key works


I'm running this Ansible ad-hoc command on Ubuntu 16.x (ansible ver. 2.2.1.0 and 2.2.2.0)

ansible host_alias -a "df -h" -u USER

where host_alias is the defined the ansible hosts file (defines an ec2 instance and its .pem file).

the host file looks like this:

[host_alias]

my_host.compute.amazonaws.com

private_key_file=/path/to/key/my_key.pem

I get this error:

private_key_file=/path/to/key/my_key.pem | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: ssh: Could not resolve hostname private_key_file=/path/to/key/my_key.pem: Name or service not known\r\n", 
    "unreachable": true
}
my_host.compute.amazonaws.com | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: Permission denied (publickey).\r\n", 
    "unreachable": true

The same host and key work fine when I ssh (defined by ~/.ssh/config). I have made triple sure the key is there and has read permissions. I also tried setting the ansible_user in the Ansible hosts file.

Any ideas?


Solution

  • Please check the format of the Ansible inventory file in the documentation.

    You have defined two hosts in a host group named host_alias:

    • the first host is: my_host.compute.amazonaws.com,

    • the second host is: private_key_file=/path/to/key/my_key.pem.

    Ansible complains it cannot connect to the second host:

    Could not resolve hostname private_key_file=/path/to/key/my_key.pem

    It also cannot connect to the first host, because the SSH key is not defined:

    Failed to connect to the host via ssh: Permission denied (publickey).


    On top of the mistake of splitting the hostname and the parameter into separate lines, you also got the name of the parameter wrong -- it should be ansible_ssh_private_key_file.

    The parameters are listed in a later section of the same document.


    Your inventory file should look like this:

    [host_group_name]
    my_host.compute.amazonaws.com ansible_ssh_private_key_file=/path/to/key/my_key.pem
    

    and your command:

    ansible host_group_name -a "df -h" -u USER