Getting dynamic variables (string) from hostvars in templates

Dear Ansible users,

I am looking for a very specific feature, and I am not sure it is possible to do it.

I have a file in my inventories/group_vars/all/test.yml with the following content:

`
test1: “{{inventory_hostname}}”

test2: “{{test1}}”

test3: “{{hostvars[inventory_hostname][‘test1’]}}”

mylist:

  • item1
  • item2
  • item3

test4: “{% for item in mylist %}{{item}} —{% endfor %}”

test5: “{{test4}}”

test6: “{{hostvars[inventory_hostname][‘test4’]}}”
`

So, it’s kind of dynamic strings.

Then using a simple role, with the following test.j2 template:

`
test1:
{{test1}}

test2:
{{test2}}

test3:
{{test3}}

test4:
{{test4}}

test5:
{{test5}}

test6:
{{test6}}

test7:
{{hostvars[‘myhost2’][‘test6’]}}

test8:
{{hostvars[‘myhost2’][‘test3’]}}

`

If I execute the template on myhost2, I get the following result:

`
test1:
myhost2

test2:
myhost2

test3:
myhost2

test4:
item1 —item2 —item3 —

test5:
item1 —item2 —item3 —

test6:
item1 —item2 —item3 —

test7:
{{hostvars[inventory_hostname][‘test4’]}}

test8:
{{hostvars[inventory_hostname]['test1']}}
`

So, each “direct” access to variables in the template, i.e. not using hostvars, is ok, but when using hostvars, it fails.

Do you know why, and how to solve this ? I can see that the content of hostvars['myhost2']['test6']`` is indeed the “static” content of test6 variable, but it was not “evaluated” more than 1 time, like when doing a direct access to the variable.

This is a very simple example here, but what I want to achieve is to access dynamic string like these using hostvars with other hosts than me, so for example, being on myhost1, and get content of what would be test3 on myhost2 (i.e. “myhost2”) using hostvars[‘myhost2’][‘test3’].

With my best regards

Ben