Determine last host in host list

I need to determine how many hosts are left to be worked on in a playbook run. I have set serial to 1 in the playbook so only one host will be worked on at a time, and I have a long pause at the bottom of the playbook to force a settling period between hosts. But if the current host is the last host in the list, there is no need to pause; the playbook can just end immediately. So, how can I determine if there are no more hosts after the current host?

Test the *last batch*. For example

    - debug:
        msg: Last batch
      when: ansible_play_hosts_all[-1] == ansible_play_batch[-1]

See "Special variables"
https://docs.ansible.com/ansible/latest/reference_appendices/special_variables.html

The next option is

       when: ansible_play_hosts_all[-1] in ansible_play_batch

But, this won't work if the order is changed. See "Ordering execution
based on inventory"
https://docs.ansible.com/ansible/latest/user_guide/playbooks_strategies.html#ordering-execution-based-on-inventory

Then, the next option is

    - set_fact:
        hleft: "{{ hostvars[ansible_play_hosts_all.0]['hleft']|
                   default(ansible_play_hosts_all)|
                   difference(ansible_play_batch) }}"
      delegate_to: "{{ ansible_play_hosts_all.0 }}"
      delegate_facts: true
    - debug:
        msg: Last batch
      when: not hostvars[ansible_play_hosts_all.0]['hleft']

That feels overly fragile and difficult to read.

I would just set a flag variable and check whether there are any hosts that don’t have it set:

tasks:

  • set_fact:
    play_is_done: true

  • debug:
    msg: I’m not last
    when: ansible_play_hosts | map(‘extract’, hostvars, ‘play_is_done’) | reject(‘defined’) | list

Some good answers! Thanks!-Mark

Consider that you have parallel execution so 'last host' might not be
the last one executing (unless serial=1 or forks=1).