Reputation: 2815
I'm trying to dynamically create a list of dictionaries in Ansible, from exiting variables which are named in a similar manner. I can't really modify the existing variables, as they are used by other things in the project.
Assuming the following variables exists already:
item_1a:
name: first test item
value: 100
item_2a:
name: second test item
value: 200
options: extra
item_zz:
name: last test item
option: nameless
What I need to create dynamically from all variables with name matching ^item_*
:
dynamic_list:
- name: first test item
value: 100
- name: second test item
value: 200
options: extra
- name: last test item
option: nameless
Can I query vars by name pattern, in any manner?
Upvotes: 1
Views: 549
Reputation: 68034
For example, the task below does the job
- set_fact:
dynamic_list: "{{ my_vars|map('extract', vars)|list }}"
vars:
my_vars: "{{ vars|select('match', '^item_.*$')|list }}"
gives
dynamic_list:
- name: first test item
value: 100
- name: second test item
options: extra
value: 200
- name: last test item
option: nameless
Upvotes: 1
Reputation: 2815
I ended up getting the list in the following way,
vars:
varname_list: "{{ query(varnames, '^item_.*$') }}"
dynamic_list: "{{ varname_list | map('extract', vars) | list }}"
Upvotes: 0