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.

1 Answer 1

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 }}"
3
  • Okay, understood. I just tested it and it's working with a normal variable declare at the top of the play. So, expansion of a variable defined via set_fact inside of hostvar does not work, yet declaring the variable the the root of the play works? Why is that? It seems that one kind of expansion works but not the other. Non-working expansion (with set_fact doing the declare): i.imgur.com/RgXAg4s.png Working expansion (variable declare at the top of play): i.imgur.com/RgXAg4s.png
    – synth45
    Commented Mar 27, 2021 at 20:02
  • 2
    You should define "It's not working" (error message, what you get vs what you expect...). In this case, I'm almost sure your problem is not related to using set_fact or not but to mandatory quotes in ansible when a value is a jinja2 exepression and starts with double moustaches: docs.ansible.com/ansible/3/user_guide/…. I also suggest you save yourself some headaches by adopting the yaml only syntax for tasks rather than the old ini style. Commented Mar 28, 2021 at 8:30
  • In case my comment was not clear enough: gist.github.com/zeitounator/8c5834bf149a514441f3cdf8cd683f05 Commented Mar 28, 2021 at 8:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.