Using ansible check ssh passwdless login, if not working, copy pub key to the remote host

ansibleansible-playbook

I am learning ansible, this is my playbook,

---
- name: Check passwdless login
  #hosts: stage-servers
  hosts: Testing-Server
  gather_facts: False
  tasks:
        - name: check ssh to remote hosts works
          register: ssh_connection_test
          shell: "hostname; id"
          ignore_errors: yes
        - debug:
             msg: "Testing ssh_connection_test.stderr"
        - name: Task passwdless login failed, do ssh-copy-id
          register: ssh_copy_id_result
          shell: "/usr/local/bin/sshpass -f ~/.ssh/psk ssh-copy-id -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa.pub \"root@{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }} \""
          when: "'.*Failed.*' in ssh_connection_test.stderr"
        - debug:
             var: ssh_copy_id_result
~*

when first task failed, the playbook not proceeding with the next task. Please help me to resolve this issue,

Output of this playbook is:

-bash-4.1# ansible-playbook passwordless.yml 

PLAY [Check passwdless login] ******************************************************************************************************************************************************************************

TASK [check ssh to remote hosts works] *********************************************************************************************************************************************************************
fatal: [x.x.x.x]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Address x.x.x.x maps to test.testlab.com, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!\r\nPermission denied (publickey,gssapi-keyex,gssapi-with-mic,password).\r\n", "unreachable": true}
    to retry, use: --limit @/etc/ansible/passwordless.retry

PLAY RECAP *************************************************************************************************************************************************************************************************
x.x.x.x                 : ok=0    changed=0    unreachable=1    failed=0

Best Answer

Change ignore_errors: yes to ignore_unreachable: yes

ignore_unreachable will allow Ansible to not fail when you hit the unreachable error you are after. This will then allow for the task to run to copy the ssh key to the remote machine.

Does require Ansible 2.7 or above

As an extra the when on the shell task can also be adjusted to

when: ssh_connection_test.unreachable is defined and ssh_connection_test.unreachable 

This uses the inbuilt bool in the returned error and also a check to make sure it is defined in case the ssh connection was successfull.