2

I have a hardcoded hostvars line, like so:

node1_hostname={{ hostvars['192.168.0.162']['node1_hostname'] }}

I have a set_fact variable from a previous play that I'd like to expand in the host section of the hostvars declaration, instead of the IP address. Can hostvars take expansion inside those brackets and single quotes?

Thanks.

Bruce Becker
  • 3,783
  • 4
  • 20
  • 41
synth45
  • 71
  • 6

1 Answers1

3

No, you cannot nest jinja2 expansion i.e. the following won't work:

# Warning ! Those will fail !
some_var: "{{ some_dict[{{ some_dynamic_key }}] }}"
other_var: "{{ {{ dynamicaly_prefixed }}_var }}"
# Did I forget to say the above examples will fail ?

But you can use your var without any problem, just as in almost any other programming language dealing with list and indexes. There is actually an ansible FAQ entry on this particular subject

some_inventory_hostname: 192.168.0.162
node1_hostname: "{{ hostvars[some_inventory_hostname].node1_hostname }}"
Zeitounator
  • 907
  • 6
  • 12