Ansible - Play with hosts in order I desire

怎甘沉沦 提交于 2020-02-20 07:56:46

问题


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_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).




回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!