Search code examples
ansibleyamlansible-inventory

How to run Ansible tasks for each server separately


I have an inventory file like below.

[all:vars]
ansible_user=root
zookeeper_new=true

[zookeepers]
10.16.0.31
10.16.0.32

Inside my .yml file where I have declared the tasks, I would like to run all of those tasks first in the server 31 and after that on server 32. Is that possible and if so, how can I do it?

Currently, it runs single tasks on both the servers and then jump to the next task. As an example;

TASK [Zookeeper/Zookeeper-New : Stop and disable existing zookeeper service] ***
ok: [10.16.0.31]
ok: [10.16.0.32]

TASK [Zookeeper/Zookeeper-New : Find previous zookeeper version directories] ***
ok: [10.16.0.32]
ok: [10.16.0.31]

Instead, what I want is

TASK [Zookeeper/Zookeeper-New : Stop and disable existing zookeeper service] ***
ok: [10.16.0.31]

TASK [Zookeeper/Zookeeper-New : Find previous zookeeper version directories] ***
ok: [10.16.0.31]

TASK [Zookeeper/Zookeeper-New : Stop and disable existing zookeeper service] ***
ok: [10.16.0.32]

TASK [Zookeeper/Zookeeper-New : Find previous zookeeper version directories] ***
ok: [10.16.0.32]

Solution

  • You should think why you need to do that and if you can achieve your goals using the "normal" way.
    If you really need to do it the way you describe, set serial: 1 on your playbook. This will cause ansible to to one host after the other.

    For example:

    ---
    - name: test play
      hosts: zookeepers
      serial: 1
      tasks:
        - name: task one
          command: hostname
    

    Check the docs for more info: