Skip to content

Ansible - Functions

Filters

Map

Search string into a list:

my_list: [yop, yap, yip, yoppa]
my_new_list: "{{ my_list | map('regex_search', 'yop.*') | select('string') | list }}"
# Result: [yop, yoppa]

Get only an attribute from a list of dict:

my_list: [{"a": "1", "b": "2"}, {"a": "10", "b": "20"}]
my_new_list: "{{ my_list | map(attribute='a') | list }}"
# Result: ["1", "10"]

Sort

Sort a list:

my_list: [1, 4, 3, 2]
my_new_list: "{{ my_list | sort(reverse=true) }}"
# Result: [4, 3, 2, 1]

Sort a list of dict:

my_list: [{"a": "1", "b": "21"}, {"a": "10", "b": "20"}]
my_new_list: "{{ my_list | sort(attribute=b) }}"
# Result: [{"a": "10", "b": "20"}, {"a": "1", "b": "21"}]

Select

Select raw with a specific attribute:

my_list: [{"a": "1", "b": "21"}, {"a": "10", "b": "20"}]
my_item: "{{ my_list | selectattr('a', 'equalto', '1') | first }}"
# Result: {"a": "1", "b": "21"}

Manipulation

Combine

Increment dict:

- name: get secrets from vault
  tags: [build_iso, vmware]
  ansible.builtin.set_fact:
    vault: "{{ vault | default({}) | combine({item.name: item.url}) }}"
  with_items: "{{ vault_secrets }}"
Back to top