Reputation: 437
Assume I have hosts with multiple (DNS) names/IPs, e.g. because they have multiple NICs and thus routes to reach them.
I want to play a playbook in case one of these routes fails. Since I do not know which one works, I would like ansible to try all of them and then play the book only once for this host. It would be easy to put all the host's names into the inventory and let it run, but then the playbook would be executed once for each name of the host.
Question: Is there a way to specify alternative host names or to tell ansible to run the playbook only on one host per group?
Upvotes: 2
Views: 2097
Reputation: 68274
It can be implemented
to run the playbook only on one host per group
See example below.
- hosts: jails-01
strategy: linear
vars:
lock_file: /var/lock/my_ansible_hostname.lock
tasks:
- name: delete lock_file
file:
path: "{{ lock_file }}"
state: absent
run_once: true
delegate_to: localhost
- name: select host
shell: "echo {{ ansible_hostname }} > {{ lock_file }}"
args:
creates: "{{ lock_file }}"
delegate_to: localhost
- name: winner takes it all
fail:
msg: "Too late. Other thread is running. End of play."
when: lookup('file', lock_file) != ansible_hostname
- name: go ahead
debug:
msg: "{{ ansible_hostname }} goes ahead ... "
# ansible-playbook playbook.yml | grep msg
fatal: [test_01]: FAILED! => {"changed": false, "msg": "Too late. Other thread is running. End of play."}
fatal: [test_03]: FAILED! => {"changed": false, "msg": "Too late. Other thread is running. End of play."}
"msg": "test_02 goes ahead ... "
Upvotes: 2