Get list of failed instances

I have roles in the playbook.

I have a dynamic inventory of hosts. *How do I get a list of failed
instances?*

For example,

    _failed: "{{ ansible_play_hosts_all|
                 difference(ansible_play_hosts) }}"

See
https://docs.ansible.com/ansible/latest/reference_appendices/special_variables.html#special-variables

Let's test it. Given the inventory

  > cat hosts
  host1 ok=true
  host2 ok=false
  host3 ok=false

The playbook

  - hosts: all
    gather_facts: false
    vars:
      _failed: "{{ ansible_play_hosts_all|
                   difference(ansible_play_hosts) }}"
    tasks:
      - assert:
          that: ok|bool
      - debug:
          var: _failed

gives

  _failed:
    - host2
    - host3

Thank you. I tried adding debug after the roles.

: “{{ ansible_play_hosts_all|
difference(ansible_play_hosts) }}”

But it lists out the wrong instances.

Not sure if it’s coz of the dynamic inventory.

This helped. Thank you so much. Much appreciated.