I am creating a simple playbook to add the current user's public key onto the remote host. My playbook fails with error "Failed to connect to the host via ssh: Permission denied".
I am running the playbook as non-root, and I can succesfully ssh to the remote host as root. I run the following script with -K and enter the become password when prompted.
---
- name: Simple test 1
hosts: all
gather_facts: no
vars:
username : "root"
pubkey : "{{ lookup('file','{{ ansible_env.HOME }}/.ssh/id_rsa.pub') }}"
tasks:
- name: Confirm this user has a public key file
delegate_to: 127.0.0.1
stat:
path: '~/.ssh/id_rsa.pub'
register: stat_result
- name: Simple test 2
hosts: all
become: true
become_user: root
tasks:
- name: Abort if this user has no public key file
fail: msg="You are missing your public key file"
when: not stat_result.stat.exists
- name: Add public key for this user to remote host
authorized_key: >
user = {{ username }}
key = {{ pubkey }}
state = present
- name: Print all available facts
ansible.builtin.debug:
var: ansible_facts
The output from running task 3 with -vvv and -K is below:
<
somehost.com> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/home/admin/.ansible/cp/bf945a50fe
somehost.com '/bin/sh -c '"'"'echo ~ && sleep 0'"'"''
<
somehost.com> (255, '', 'Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).\r\n')
"changed": false,
"msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",
"unreachable": true
}
Notice authorized_key seems to run as user None (despite telling task 3 to become root). Only by setting ansible_ssh_user and ansible_ssh_pass in the ansible hosts file can I get authorized_key to work. Why?
I'm confused!
1. Shouldn't the -K parameter cause ansible to use the password I enter for ssh authentication?
2. Shouldn't the become: true cause the authorize_key to login to the remote host as root?
3. Can someone explain the relationship between 'become' & '-K' and ansible_ssh_user & ansible_ssh_pass (set in the hosts file)