Ansible - Play with hosts in order I desire

Applicable for Ansible 2.4 and higher:

This is now the default behaviour, ansible will play the hosts in the order they were mentioned in the inventory file. Ansible also provides a few built in ways you can control it with order:

- hosts: all
  order: sorted
  gather_facts: False
  tasks:
    - debug:
        var: inventory_hostname

Possible values of order are:

  • inventory: The default. The order is ‘as provided’ by the inventory
  • reverse_inventory: As the name implies, this reverses the order ‘as provided’ by the inventory
  • sorted: Hosts are alphabetically sorted by name
  • reverse_sorted: Hosts are sorted by name in reverse alphabetical order
  • shuffle: Hosts are randomly ordered each run

Source: https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html#hosts-and-users


Edit: The best solution is in dubes' answer but this one gives you more freedom in case specific operations have to be applied to the host list, or you can't use Ansible 2.4.

Since Ansible 2.2 you can use ansible_play_hosts or ansible_play_batch and sort it:

---
- hosts: "{{ ansible_play_hosts | sort() }}"

From ansible doc:

ansible_play_hosts is the full list of all hosts still active in the current play.

ansible_play_batch is available as a list of hostnames that are in scope for the current ‘batch’ of the play. The batch size is defined by serial, when not set it is equivalent to the whole play (making it the same as ansible_play_hosts).

Tags:

Ansible