简体   繁体   中英

Ansible, dynamically create list of dictionaries from pattern match of variable names

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?

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

I ended up getting the list in the following way,

  vars:
    varname_list: "{{ query(varnames, '^item_.*$') }}"
    dynamic_list: "{{ varname_list | map('extract', vars) | list }}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM