Problem statement

When running Ansible playbooks, sometimes some of your hosts are unreachable—maybe because of network problems, reboots, or just being offline. By default, if a host is down, Ansible will mark it as failed, which can interrupt your automation or make the output messy and hard to read.

To avoid this, it’s useful to check which hosts are actually reachable before running the main tasks. This way, your playbook only targets the hosts that are up, making your automation more stable and easier to manage.

Linux version

- name:  play1 | get alive hosts
  hosts: proxmox
  gather_facts: false # may fail otherwise
  tasks:
    - name: check
      vars:
        ansible_ssh_common_args: '-o ConnectTimeout=5'
        ansible_command_timeout: 5
      ping:
      register:           ping_result
      ignore_unreachable: true
      ignore_errors:      true
      no_log:             true
    - name: ignore them
      meta: end_host
      when: ping_result is failed
    - name: group reachable_proxmox
      group_by:
        key: reachable_proxmox
      when: ping_result.ping == 'pong'
      ignore_unreachable: true
      ignore_errors:      true
      no_log:             true
- name: play2 | exec on alive hosts
  hosts:        reachable_proxmox
  gather_facts: no
  tasks:
    - name: do something
      debug:
        msg: "xx"

Mikrotik version

Community.Routeros collection doesn’t have a module like ping to compare the “pong” response. And in general with Linux ping module uses python (which is not present in routeros). Here you can use any command that will run. I’ve also tried fact gathering but there are a lot of them and it’s totally unnecessary

- name: play1 | get alive hosts
  hosts: mikrotiks
  gather_facts: false
  tasks:
    - name: Collect all facts from the device
      vars:
        ansible_command_timeout: 30 # limit time and override ansible.cfg
      community.routeros.command:
        commands:
          - '/system/resource/print'
      register:           ping_result
      ignore_unreachable: true
      ignore_errors:      true
    - name: stop execution for unreachable hosts
      meta: end_host
      when: ping_result is failed
    - name: group reachable hosts
      group_by:
        key: reachable_hosts
      when:               ping_result is not failed # main here
      ignore_unreachable: true
      ignore_errors:      true

- name: play2 | exec on alive hosts
  hosts:        reachable_hosts
  gather_facts: no
  tasks:
    - name: do something
      community.routeros.command:
        commands:
          - '/log/print'