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
  • 61,569
  • 11
  • 147
  • 305

1 Answers1

1

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'kk 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
  • 61,569
  • 11
  • 147
  • 305