Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible - how to control the order of the hosts when playbook is ran

Tags:

ansible

Let's say that we have defined two machines in our inventory file:

[db-server-preprod] 172.16.0.1 172.16.0.2

If I run a playbook against this group will run in the same time on both machines if serial is 0 or sequentially if is 1 and the order seems to be the one in which the IPs are defined in the group.

But the question is if can I control the order of the playbook execution on the defined machines?

The same role behaves slightly different for one of the machines (the master) as opposed to all the others but is important that the machine that I want to be the master will be the first one on which the playbook executes.

My ideas so far:

  • create different group names in which the order of the IPs is reversed and based on needs run on one host or another but the disadvantage is that I think I would need to duplicate group_vars so there will be one for each db-server-preprod* variant + all the other environments.
  • separate the installation on two different roles - one for master and for standby servers and based on the needs I will run the one that I want on which machine I want.
like image 504
cristian.andrei.stan Avatar asked Feb 22 '17 08:02

cristian.andrei.stan


People also ask

In what order does Ansible playbook is executed?

A playbook runs in order from top to bottom. Within each play, tasks also run in order from top to bottom.

How do I control Ansible playbook only on specific hosts?

Using the --limit parameter of the ansible-playbook command is the easiest option to limit the execution of the code to only one host. The advantage is that you don't need to edit the Ansible Playbook code before executing to only one host.

Which hosts are randomly ordered each run?

shuffle: Hosts are randomly ordered each run.

Does Ansible work in sequential manner?

Ansible playbooks are written in YAML format, and they contain multiple tasks executed in sequential order.


1 Answers

You may place your master host into separate group, then apply common role to all servers at once, then apply master-roles only to master server, and slave-roles to all servers except master using excluding pattern.

Inventory:

[all-servers]
host1
host2
host3
host4

[master-server]
host2

Playbook:

---
- hosts: all-servers
  gather_facts: no
  tasks:
    - debug: msg=role-common

- hosts: master-server
  gather_facts: no
  tasks:
    - debug: msg=role-master

- hosts: all-servers:!master-server
  gather_facts: no
  tasks:
    - debug: msg=role-slave
like image 171
Konstantin Suvorov Avatar answered Oct 21 '22 05:10

Konstantin Suvorov