Ansible jinja templating: variable number of group keys

Viewed 104

I'm writing a shell ansible script and one of the things I need to do is populate a list in an ini file from an inventory file using jinja2.

Currently it takes in variables component_group_1 and component_group_2 for group keys and populates a list of components from there

components: "{{groups[component_group_1]+groups[component_group_2]}}"

How can I rewrite this line so that it so that it can take just a single variable named all_component_groups, which has all the needed group keys in this pattern 'customers,vendors,products....', and where there can be any number of group keys?

1 Answers

It would be much easier to have your var as a list:

all_component_groups_list:
  - group1
  - group2
  - group3

Meanwhile, it's quite easy to create a list from your pattern

all_components_groups: "customers,vendors,products"
all_components_groups_list: "{{ all_components_groups.split(',') }}"

Once you got that the rest is also quite easy:

  1. extract the relevant lists from the groups dict with map => extract
  2. flatten the list of lists to get a single one containing all values
  3. use the unique filter to remove possible duplicated values

Putting it all together from your coma separated list requirement

components: "{{ all_component_groups.split(',') | map('extract', groups) | flatten | unique }}"
Related