How to loop over hosts data from a Yaml file in Ansible
I had an inventory file in this format in Yaml:
cluster: hosts: 192.168.0.79: name: node1 192.168.0.86: name: node2
And I want to loop over the names of all hosts when processing each host.
This seems to work in the playbook:
- hosts: cluster tasks: - debug: msg: "Computer is {{ hostvars[item]['name'] }}" with_items: "{{ groups['cluster'] }}"
This threw me a bit, albeit I am new to Ansible. It seems to me that the Yaml structure in the inventory file implies that there is a one key dictionary (to use python lingo, which is appropriate I believe for Ansible). So something like this:
{'cluster': {'hosts': {'192.168.0.79': {'name':'node1'}, '192.168.0.86': {'name':'node2'} } } }
However looking at the working code in the playbook, first it seems to be wrapped in a magical key "groups" (maybe this is standard for inventory files, I don't know), then you get the next magical variable "item" which points to the key of the dictionary under "hosts" which means we have somehow jumped past "hosts". Ok, so can I get deeper into the data with item? Nope, that's it. But wait, maybe it is treated as a name space so I can just write {{name}}? Yay it works! No, wait that is the wrong name. It is the name of the host I am configuring.