Ansible - Variable expansion inside hostvars declaration? 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.
No, you cannot nest jinja2 expansion i.e. the following won't work:
# Warning ! Those will fail !
some_var: &quot;{{ some_dict[{{ some_dynamic_key }}] }}&quot;
other_var: &quot;{{ {{ dynamicaly_prefixed }}_var }}&quot;
# 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: &quot;{{ hostvars[some_inventory_hostname].node1_hostname }}&quot;