How do you transform lists and dicts with filters (`map`, `select`, `selectattr`, `unique`, `flatten`)?
IntermediateConceptJinja2, Conditionals and Loops
Answer
vars:
users:
- { name: alice, admin: true }
- { name: bob, admin: false }
admin_names: "{{ users | selectattr('admin') | map(attribute='name') | list }}"
all_groups: "{{ [['a','b'], ['b','c']] | flatten | unique }}"
ports: "{{ services | map(attribute='port') | select('gt', 1024) | list }}"
select/reject filter by a test, selectattr/rejectattr filter dicts by attribute, and map projects values. Most filter results are generators, so add | list to get a real list.
More on Jinja2, Conditionals and Loops
What role does Jinja2 play in Ansible?BeginnerWhat are the three Jinja2 delimiters?BeginnerShow a template with a loop and a conditional, and how it is deployed.BeginnerWhich filters do you use every day?BeginnerHow does `when` work and which operators can you use?BeginnerHow do you combine several conditions?Beginner