问题
When running a playbook Ansible randomly sets a node as first, second and third.
TASK [setup] ********
ok: [node-p02]
ok: [node-p03]
ok: [node-p01]
How can I configure Ansible to ensure it plays as:
TASK [setup] ********
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.
回答1:
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
回答2:
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_hostsis the full list of all hosts still active in the current play.
ansible_play_batchis 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).
回答3:
I figured that another possibility is to use the exact hostnames in the hosts as a list, instead of a group. However, answers provided above are better.
---
- hosts:
- node-p01
- node-p02
- node-p03
来源:https://stackoverflow.com/questions/42506865/ansible-play-with-hosts-in-order-i-desire