Ansible – Use values in a loop from hosts file on another host


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:

db1 ansible_host=
db2 ansible_host=
db3 ansible_host=


Add the “role” key with the necessary value for each host in the “db” group:

db1 role=development ansible_host=
db2 role=staging ansible_host=
db3 role=production ansible_host=


Playbook example:


- name: management
  gather_facts: No
  hosts: management
    - name: debug
        msg: "Instance {{ item.1 }} with IP {{ hostvars[ item.1 ].ansible_host }} is {{ hostvars[ item.1 ].role}}"
      with_indexed_items: "{{ groups['db'] }}"



ok: [management] => (item=[0, u'db1']) => {
    "msg": "Instance db1 with IP is development"
ok: [management] => (item=[1, u'db2']) => {
    "msg": "Instance db2 with IP is staging"
ok: [management] => (item=[2, u'db3']) => {
    "msg": "Instance db3 with IP is production"

Tagged: Tags

Notify of

Inline Feedbacks
View all comments