---
- name: Determine whether to connect as root or admin_user
  local_action: shell ssh -o PasswordAuthentication=no root@{{ inventory_hostname }} "echo can_connect"
  failed_when: false
  changed_when: false
  register: root_status

- name: Set remote user for each host
  set_fact:
    ansible_ssh_user: "{{ (root_status.stdout == 'can_connect') | ternary('root', admin_user) }}"

---
- name: Determine whether to connect as root or admin_user
  local_action: command ansible {{ inventory_hostname }} -m ping -i {{ inventory_file }} -u root
  failed_when: false
  changed_when: false
  register: root_status

- name: Set remote user for each host
  set_fact:
    ansible_ssh_user: "{{ (root_status.rc == 0) | ternary('root', admin_user) }}"

- name: Announce which user was selected
  debug:
    msg: "Note: Ansible will attempt connections as user = {{ ansible_ssh_user }}"

Use ansible ping module to determine remote user
Use ansible ping module to determine remote user
