Skip to content. | Skip to navigation

Personal tools
Log in
You are here: Home How to loop over hosts data from a Yaml file in Ansible

How to loop over hosts data from a Yaml file in Ansible

published May 03, 2017 06:40   by admin ( last modified May 03, 2017 08:46 )

I had an inventory file in this format in Yaml:

      name: node1
      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
  - 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:


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.