hostvars vs lookup(vars)

32 views
Skip to first unread message

rjwagn...@gmail.com

unread,
Mar 21, 2024, 9:25:04 AM3/21/24
to Ansible Project
This question is targeted at Matt Martz and Brian Coca (but anyone should feel free to jump in).  I recently asked a question about how to access a variable in a task.  Matt, you recommended hostvars[inventory_hostname][item], and Brian, you recommended lookup('vars', item).  I remember a discussion that included you both a few years ago where Matt, you promoted hostvars, and Brian, you promoted vars, but I can't remember where it was (freenode?  github?).  So each of you has a preference, and I'm curious why.  Both are documented approaches, but I don't see any documentation around the subtleties associated with each   Care to share?

Thanks
Rob

Brian Coca

unread,
Mar 21, 2024, 9:50:34 AM3/21/24
to ansible...@googlegroups.com
Both are valid approaches but do different things, hostvars will
provide a untemplated subset of what you can get through the vars
lookups for the case of 'inventory_hostname', but the lookups do not
currently expose hostvars for other hosts.

--
----------
Brian Coca (he/him/yo)

Rob Wagner

unread,
Mar 25, 2024, 11:14:58 AM3/25/24
to ansible...@googlegroups.com
I think I got it.  Thanks Brian

--
You received this message because you are subscribed to a topic in the Google Groups "Ansible Project" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/ansible-project/rI_EW6uFgjM/unsubscribe.
To unsubscribe from this group and all its topics, send an email to ansible-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/CACVha7eaZH0kEpbOSgToZ8PPtt%3DwdiCg7cV8vQ2x-zhkgk3Z5A%40mail.gmail.com.

Brian Coca

unread,
Mar 25, 2024, 12:08:18 PM3/25/24
to ansible...@googlegroups.com
A small rephrase as my statement above is not fully true:

hostvars are templated but restricted to variables in the hostvars for
that host itself, so hostvars that depend on variables in other scopes
are not templated. Under the hood templating fails but this is non
fatal as we expect it often, so we return the original template.
Using the vars directly in the context of the host elsewhere will '
just work'TM as there the rest of the vars exist in that context.

----------
Brian Coca (he/him/yo)

Reply all
Reply to author
Forward
0 new messages