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

35 views
Skip to first unread message

onenessboy

unread,
Dec 6, 2018, 5:43:12 AM12/6/18
to Ansible Project

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...

Ravi Ranjan

unread,
Dec 7, 2018, 12:03:10 AM12/7/18
to Ansible Project
I am checking this one and update you

Brian Coca

unread,
Dec 7, 2018, 5:07:29 PM12/7/18
to Ansible Project
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).

--
----------
Brian Coca
Reply all
Reply to author
Forward
0 new messages