There is a "hosts" file in which there is a group of "db". These are database instances that play a different role. The goal is to add the role type to the "hosts" file, so that later we can use this value in a loop that will be executed on a completely different host, for example "management"
Source "hosts" file:
[db] db1 ansible_host=192.168.1.101 db2 ansible_host=192.168.1.102 db3 ansible_host=192.168.1.103
Add the "role" key with the necessary value for each host in the "db" group:
[db] db1 role=development ansible_host=192.168.1.101 db2 role=staging ansible_host=192.168.1.102 db3 role=production ansible_host=192.168.1.103
Playbook example:
--- - name: management gather_facts: No hosts: management tasks: - name: debug debug: msg: "Instance {{ item.1 }} with IP {{ hostvars[ item.1 ].ansible_host }} is {{ hostvars[ item.1 ].role}}" with_indexed_items: "{{ groups['db'] }}"
Output:
ok: [management] => (item=[0, u'db1']) => { "msg": "Instance db1 with IP 192.168.1.101 is development" } ok: [management] => (item=[1, u'db2']) => { "msg": "Instance db2 with IP 192.168.1.102 is staging" } ok: [management] => (item=[2, u'db3']) => { "msg": "Instance db3 with IP 192.168.1.103 is production" }