When running a playbook Ansible randomly sets a node as first, second and third.
ok: [node-p02]
ok: [node-p03]
ok: [node-p01]
Q: How can I configure Ansible to let it execute with the hosts in sorted order? Example:
ok: [node-p01]
ok: [node-p02]
ok: [node-p03]
Serial: 1
is not an option, since it slows down the play, and my playbook is meant for 3 nodes in a single play.
Within each play, tasks also run in order from top to bottom. Playbooks with multiple 'plays' can orchestrate multi-machine deployments, running one play on your webservers, then another play on your database servers, then a third play on your network infrastructure, and so on.
They are like a to-do list for Ansible that contains a list of tasks. Playbooks contain the steps which the user wants to execute on a particular machine. Playbooks are run sequentially.
Ansible uses a combination of a hosts file and a group_vars directory to pull variables per host group and run Ansible plays/tasks against hosts. group_vars/all is used to set variables that will be used for every host that Ansible is ran against.
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:
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 byserial
, when not set it is equivalent to the whole play (making it the same asansible_play_hosts
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With