Example of a complete playbook
- hosts: localhost
vars:
my_vars:
- {name: "a", surname: "b", status: "c"}
- {name: "d", surname: "e", status: "f"}
- {name: "g", surname: "h", status: "i"}
my_vals: "{{ my_vars|json_query('[].[name, surname, status]')|
map('join', '/')|
list }}"
my_urls: "{{ ['http://company.com/']|product(my_vals)|
product(['.txt'])|
map('flatten')|
map('join')|
list }}"
my_urls_dict: "{{ my_urls|map('community.general.dict_kv', 'url')|
list }}"
tasks:
- debug:
var: my_urls
- debug:
var: my_urls_dict
Q: "How can I create a loop on objects with status: 'f' ?"
A: Select the item. For example,
- debug:
var: item
loop: "{{ my_vars|selectattr('status', 'eq', 'f') }}"
gives
TASK [debug] ************************************************************
ok: [localhost] => (item={'name': 'd', 'surname': 'e', 'status': 'f'}) =>
ansible_loop_var: item
item:
name: d
status: f
surname: e
But this answer seems to be too obvious. You're probably asking how to select such an item when the url is created. There are many options:
- For example, combine the dictionaries
my_urls_dict: "{{ my_urls|map('community.general.dict_kv', 'url')|
zip(my_vars)|
map('combine')|
list }}"
gives
my_urls_dict:
- {name: a, status: c, surname: b, url: 'http://company.com/a/b/c.txt'}
- {name: d, status: f, surname: e, url: 'http://company.com/d/e/f.txt'}
- {name: g, status: i, surname: h, url: 'http://company.com/g/h/i.txt'}
Then, the iteration is as trivial as before.
- debug:
var: item
loop: "{{ my_urls_dict|selectattr('status', 'eq', 'f') }}"
- The next option is the iteration of both lists together
- debug:
var: item
with_together:
- "{{ my_vars }}"
- "{{ my_urls }}"
when: item.0.status == 'f'
- The trivial option would be the concatenation of the url in the loop
- debug:
var: url
loop: "{{ my_vars|selectattr('status', 'eq', 'f') }}"
vars:
url: "http://company.com/{{ item.name }}/{{ item.surname }}/{{ item.status }}.txt"