How can I assign a variable to other variables in Ansible in the correct way?

I am having an unexpected problem with Ansible. Here's a simplified example.

I have defined some global variables in group_vars / all file like this:

node01: {ipv4_address: '', some_info: data}


And use it in your inventory file:

phyn01 node="{{ node01 }}" ansible_ssh_host="{{ node.ipv4_address }}"


The funny thing is that Ansible can ssh to each of the hosts and get the facts. But I cannot get the value of the <node variable for each host when executing the playbook (I have additional data).

Working example:

- hosts: physical-hosts
    - name: get node variable for current host
      debug: var=node


The output in this case:

TASK: [get node variable for current host] ************************************
ok: [phyn01] => {
    "node": {
        "ipv4_address": "",
        "some_info": "data"


But I cannot get the same thing if I use the following:

- hosts: physical-hosts
  - debug: var=hostvars.{{item}}.node
    with_items: groups['physical-hosts']


It reports the following as an incorrect answer:

TASK: [debug var=hostvars.{{item}}.node] **************************************
ok: [phyn01] => (item=phyn01) => {
    "hostvars.phyn01.node": "{{ node01 }}",
    "item": "phyn01"



  • I need to access 'some_data' for each host in a group without redefining the same variables again for each host separately (a lot of duplicate code => a lot of errors)
  • As you can see from the example, they seem to me to be clear. And it works when we connect to the host (ansible_ssh_host resolves correctly) and the individual "var = node" resolves correctly too. The facts are delivered, of course.
  • This method only fails when I am trying to get this data for the whole group and it seems that I am using the wrong syntax.

So the questions:

  • How do I get 'some_data' for each host?
  • How to define host = hostN correctly? I need to use the same constructs as node.some_data for each host, and every time I have to define ansible_ssh_host because the same hosts can be in different groups (with different data).

Thanks for your attention

upd : I was writing from memory, so there were a lot of errors. Now output and typos are real and fixed


source to share

1 answer

for point 3 or your first question: to access data of hosts in a group you can use hosts, first you need to create a task for all hosts or interest group. for example an internal role that just does a trivial thing on all hosts. This role then collects facts from all hosts and adds them to the host group. be sure to include fact-gathering rather than limiting your play's run or skipping over that role / task. also if your vars are not simple vars like lists or dicts it is better to place their host_vars files.

This was discussed earlier in the list:!msg/Ansible-project/f90Y4T4SJfQ/L1YomumcPEQJ

didn't understand your second question, your inventory is working fine.



All Articles