Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible - Play with hosts in order I desire

Tags:

ansible

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.

like image 609
Kevin C Avatar asked Feb 28 '17 10:02

Kevin C


People also ask

Do Ansible playbooks run in order?

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.

Does Ansible run sequentially?

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.

How do I Group hosts in Ansible?

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.


2 Answers

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

like image 82
dubes Avatar answered Sep 28 '22 05:09

dubes


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

like image 29
sm4rk0 Avatar answered Sep 28 '22 04:09

sm4rk0