0

Given a list of variable names, I want to look them up and return a list of their values.

Writing such a list manually is tedious and somewhat less readable:

my_list:
- "{{ foo }}"
- "{{ bar }}"
# ...

It's possible to write it with just one pair of {{ }}, but then it results in a potentially very long, single-line expression.

mylist: "{{ [foo, bar, ...] }}"
Petr
  • 62,528
  • 13
  • 153
  • 317

2 Answers2

1

Use the vars lookup:

{{ query('vars', *my_list) }}

The * is the trickiest part of this Jinja expression, because it’s a Pythonism. It takes the list and unpacks it into positional arguments. If you leave off the * you’re passing in the list as a single argument, and the vars lookup doesn’t expect a list so it will fail.

flowerysong
  • 2,921
  • 4
  • 13
0

This expression worked quite well for me:

vars:
  my_list: "{{ variable_names|map('extract', vars)|map('mandatory') }}"
  variable_names:
  - foo
  - bar
  # ...

The trick is to use extract to look up names in the special variable vars (which I couldn't find officially documented anywhere - I'll be happy to learn).

Using map('mandatory') ensures that Ansible won't silently skip missing variables (if so desired).


Yet another alternative is to use YAML multi-line strings to split a list to multiple lines:

my_list: >-
  {{ [
  foo,
  bar,
  baz,
  ] }}
Petr
  • 62,528
  • 13
  • 153
  • 317
  • `vars` is an undocumented internal variable with some surprising behaviour and should not be used. The only reason it is only still present because there's not yet a clean deprecation path for removing it. The `vars` lookup is the supported method of retrieving vars. – flowerysong Jun 05 '22 at 15:46
  • Could you please suggest how to express the solution without using `vars`? – Petr Jun 06 '22 at 05:28