Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for a task on host A to be completed before running a task on host B on a single playbook

Tags:

ansible

I'm looking for a way to run a task on host A to be completed before running another task on host B.

---
- hosts: A
  tasks:
    - name: Do stuff
    
- hosts: B
  tasks: # <= Run this once the "Do stuff" task is over and successful
    - name: Do other stuff 

Until now I've been using two playbooks and run the one with A first. What's the best way to achieve this?

like image 391
shellwhale Avatar asked Sep 20 '25 09:09

shellwhale


2 Answers

The default behavior in ansible is actually that tasks within a playbook are run consecutively rather than in parallel.

However, ansible will by default progress with subsequent tasks even after encountering a failure. You can avoid the second task being executed by forcing errors to be treated as fatal, like this:

---
- hosts: A
  tasks:
    - name: Do stuff
  any_errors_fatal: true
    
- hosts: B
  tasks: # <= Run this once the "Do stuff" task is over and successful
    - name: Do other stuff 
like image 138
costaparas Avatar answered Sep 23 '25 10:09

costaparas


Not sure if I understood correctly but maybe this approach will help you:


---
- hosts: A
  tasks:
    - name: Spin up a VPS
    # Do your stuff and some kind of verification e.g
      shell: '<insert command here>'
      register: host_uptime
      
    
- hosts: B
  tasks: # <= Run this once theverification task is over and successful
    - name: Install curl
      package:
        name: "curl"
        state: present
        when: "{{ host_uptime.rc }}" == 0
like image 34
dejanualex Avatar answered Sep 23 '25 10:09

dejanualex