Dynamically change the order of hosts ansible runs on

This might be a newbie question, but I can’t figure out how to without writing a wrapper around ansible, or invoking ansible multiple times

Let’s say this is my inventory:

[some_service]
A
B
C

Some_service runs in synchronization mode so one is the master, which need to be shut down last.

The trouble is I do not know without actually running “some_command” which one is the master, so the shutdown order might be B->C->A or A->C->B, etc.

Is it possible to have ansible runs normally over these hosts, read the exit status of “some_command” and then delay executing shutdown on master until the others are done?

To handle this, I would create a custom fact (http://docs.ansible.com/playbooks_variables.html#local-facts-facts-d) that returned whether the current host is in the master state. Then you could write two tasks as follows:

  • name: shut down non-masters

← whatever method you’re using to shut things down, ie. service, etc.

when: not ansible_local.master_status.is_master

  • name: shut down the master last

← whatever method you’re using to shut things down, ie. service, etc.

when: ansible_local.master_status.is_master

Assuming the local fact was named “master_status.fact” and it returned JSON like {‘is_master’: true}.

I’d do it by putting the head node into a group of it’s own, to make it more explicit

  • hosts: cluster
    tasks:

  • hosts: cluster:!head_node
    tasks:

  • hosts: head_node
    tasks:

Just personal preference but where I can avoid if conditionals, I try to. Ansible likes to avoid programming constructs when it can.

Add to that creation of dynamic group from hosts or ips:
https://coderwall.com/p/cz-pjw

and you can populate your “head_node” group early in playbook and then play by Michael’s suggestion for full nirvana :slight_smile:

Hi James,
I have a doubt on your comment, Ansible runs playbook in order A,B,C for example and server B is a master server for example. How ansible runs shut down on C before B? It actually goes order A,B,C. Do you mean put the mentioned tasks in handler or tasks? I completely dint not get how we achieve this. Please give me some more details on this. Thanks.