How to tell ansible to do conditional execution based on status of hosts in invetory file.

Dear Experts,

I have a host file like something below:

`

[servers]
1.2.3.4
1.2.3.5
1.2.3.6

`

and also i have a script called test like

ansible servers -m -shell "docker ps"

Now as per my understanding the script will run on all hosts of group called servers correct ?

if yes, then I dont want ansible to run that code all hosts.

  • check first node that 1.2.3.4 if its reachable then ssh into to execute above code (test)…skip next two hosts as first node is reachable and there is no need for second and third node.
  • if first node in group not reachable, then try to connect 1.2.3.5 and execute the test code… else skip move to next check

so how can we achieve this kind or orchestration on ansible inventory hosts ?

can some guide me…

I am checking this one and update you

You need a play:

- hosts: localhost
  gather_facts: false
  tasks:
    - shell: docker ps
      delegate_to: '{{item}}'
      with_items: '{{groups["servers"]}}'
      register: mytest
      when: mytest is undefined or mytest is failed

basically you are looping over the group and will execute the task
when 'test is undefined' which means that you never ran the task
(first host) or test is defined but has failed (only if previous hosts
failed, skip if previous succeed or skipped).