Wernfried Domscheit
Wernfried Domscheit

Reputation: 59456

Run ansible tasks on hosts one-by-one

I like to upgrade my MongoDB and I created a playbook like this:

- hosts: all
  tasks:

  - name: Shutdown mongod service
    service:
      name: mongod
      state: stopped

  - name: Replace MongoDB binaries
    yum:
      name: mongod-org
      state: present

  - name: Start mongod service
    service:
      name: mongod
      state: started

Problem is, ansible first stops the service on all hosts which makes my application unavailable, then upgrades on all and finally start the service again on all hosts.

How to run these task sequentially for each host, i.e.

  1. go to first host
  2. stop service
  3. replace binaries
  4. start service
  5. repeat on next host till all hosts are done

I tried with block and include_tasks but the result is always this:

TASK [Shutdown mongod service] ***********************************************
changed: [d-mipmdb-cfg-01]
changed: [d-mipmdb-cfg-03]
changed: [d-mipmdb-cfg-02]

TASK [Replace MongoDB binaries] ******************************************************************************
changed: [d-mipmdb-cfg-01]
changed: [d-mipmdb-cfg-03]
changed: [d-mipmdb-cfg-02]

TASK [Start mongod service] ******************************************************************************
changed: [d-mipmdb-cfg-03]
changed: [d-mipmdb-cfg-01]
changed: [d-mipmdb-cfg-02]

Upvotes: 0

Views: 732

Answers (1)

hymie
hymie

Reputation: 2058

https://docs.ansible.com/ansible/latest/user_guide/playbooks_strategies.html

By default, Ansible runs in parallel against all the hosts in the pattern you set in the hosts: field of each play. If you want to manage only a few machines at a time, for example during a rolling update, you can define how many hosts Ansible should manage at a single time using the serial keyword:

- name: test play
  hosts: webservers
  serial: 2
  gather_facts: False

  tasks:
    - name: first task
      command: hostname
    - name: second task
      command: hostname

Upvotes: 2

Related Questions