Search code examples
ansiblehosts

Ansible Inventory Not Ordering Alphabetically


I'm having the following Ansible hosts file:

# Contains the host mappings
[master]
m1.my-host.com ansible_host=192.168.0.100

[node]
n1.my-host.com ansible_host=192.168.0.102
n2.my-host.com ansible_host=192.168.0.103

[k3s_cluster:children]
master
node

[all:vars]
ansible_python_interpreter=/usr/bin/python3

In my playbook, I'm saying that I need an ordered execution like this:

---
- name: Setup hostname, users and groups
  hosts: all
  order: sorted
  gather_facts: true
  remote_user: myuser
  become: yes

  roles:
    - {role: common, tags: ['host', 'system']}

But when I ran it, I get to see the following:

TASK [Gathering Facts] **********************************************************************************************************************************************************************************************
ok: [n1.my-host.com]
ok: [n2.my-host.com]
ok: [m1.my-host.com]

I would have rather expected it to be m1, n1 and then n2. Is there any idea as to why the sort order is not respected?


Solution

  • The sort order is being respected, but because Ansible executes tasks against multiple hosts in parallel, you see the results in the order in which the task completes.

    If you were to serialize your task execution like this:

    - hosts: all
      order: sorted
      serial: 1
      gather_facts: false
      tasks:
        - ping:
    

    You would see that the order of execution is consistently:

    1. m1.my-host.com
    2. n1.my-host.com
    3. n2.my-host.com

    Generally you don't want to serialize execution like that because it dramatically increases the runtime of your playbook, but if you have a very large number of hosts it sometimes makes sense to use a number > 1 to execute tasks in batches.