Test SSH connection with the Ansible ping module

---
###
## First play: Dynamically configure SSH user based on test
##
- hosts: "{{ host_group }}"
  gather_facts: false  # don't try to ssh yet!!
  vars:
    ansible_ssh_user: "{{ username }}"

  tasks:
    - name: "Test SSH connection"
      ping:  # <-- no args needed
      ignore_unreachable: true
      ignore_errors: true
      changed_when: false
      register: ssh_test

    - name: "Fall back to root user?"
      when: ssh_test.unreachable is defined
      connection: local
      set_fact:
        ansible_ssh_user: root


###
## Next play: Do something 
###
- hosts: "{{ host_group }}"
  tasks:
    - name: your task here
      # ...

Comments