This week I was updating some Ansible application and OS update playbooks. By default, when you run ansible-playbook it will apply your desired configuration to hosts in the order they are listed in the inventory file (or in the order they are returned by a dynamic inventory script). But what if you want to process hosts in a random order? Or by their sorted or reverse sorted names? I recently came across the order option, and was surprised that I didn’t notice this before.
The order option allows you to control the order ansible operates on the hosts in your inventory. It currently has five options:
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
So if you want to process your hosts in a random order, you can pass “shuffle” to option:
---
- hosts: "{{ server_list }}"
become: true
serial: 1
order: shuffle
tasks:
- name: Upgrade Operating System packages
yum:
name: '*'
state: latest
register: yum_updates_applied
...
This is super useful for large clusters, epsecially those that have hosts grouped by functional purpose. Nifty option!