Question:
I have an object like that
1 2 3 4 |
objs: - { key1: value1, key2: [value2, value3] } - { key1: value4, key2: [value5, value6] } |
And I’d like to create the following files
1 2 3 4 5 |
value1/value2 value1/value3 value4/value5 value4/value6 |
but I have no idea how to do a double loop using with_items
Answer:
Take a look at with_subelements
in Ansible’s docs for loops.
- You need to create directories:
- Iterate though
objs
and create files:
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
--- - hosts: localhost gather_facts: no vars: objs: - { key1: value1, key2: [ value2, value3] } - { key1: value4, key2: [ value5, value6] } tasks: - name: create directories file: path="{{ item.key1 }}" state=directory with_items: objs - name: create files file: path="{{ item.0.key1 }}/{{ item.1 }}" state=touch with_subelements: - objs - key2 |
An output is pretty self explanatory, the second loop iterates through the values the way you need it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
PLAY [localhost] ************************************************************** TASK: [create files] ********************************************************** changed: [localhost] => (item={'key2': ['value2', 'value3'], 'key1': 'value1'}) changed: [localhost] => (item={'key2': ['value5', 'value6'], 'key1': 'value4'}) TASK: [create files] ********************************************************** changed: [localhost] => (item=({'key1': 'value1'}, 'value2')) changed: [localhost] => (item=({'key1': 'value1'}, 'value3')) changed: [localhost] => (item=({'key1': 'value4'}, 'value5')) changed: [localhost] => (item=({'key1': 'value4'}, 'value6')) PLAY RECAP ******************************************************************** localhost : ok=2 changed=2 unreachable=0 failed=0 |