Could someone let me know how we can create a code as below?
- name: TEST1
set_fact:
list_a: "{{ list_a + [item.json.SearchResult.resources] }}"
with_items:
- "{{ source_list.results[0] }}"
- "{{ source_list.results[1] }}"
- "{{ source_list.results[x] }}"
... (unknown how many items in result from API)
vars:
list_a: []
source_list.results[x]
comes from an API result. The reason why I need to create an array is that the number of API result is maximum 100. But there are over 500 items.
2
Answers
After reading @Zeitounator's answer, I realized I was taking this the wrong way. I used the idea in the answer (
json query
andflatten
) and I changed my task to the below which works as expected.Note: since we have no idea what you initial data structure looks like exactly, the below might not be 100% fitting your use case. For your next questions, please read How to ask and pay attention to the Minimal, complete and reproducible example section. Thanks
You are taking this the wrong way. Simply extract the attribute you need from each result using the
map(attribute=x)
Jinja2 filter.For the below I inferred (see above note) that:
ansible.builtin.uri
in a loop to get batches of 100 results which are returned as a list in theSearchResult.ressources
fieldresources
are at top levelYou actually don’t need to
set_fact
:loop
or a module param….) or eventually declare this in a var at task level.source_list
var. In that case, just add a default value to prevent an error if API was not yet called.Example for the second case above in this pseudo playbook
Now, to still give a direct answer to your initial question: you can construct that list iteratively inside a
set_fact
task. This is definitely not efficient as it involves a task running inside a loop (both unneeded as demonstrated above) and possibly on multiple hosts in your play. But for learning purpose, here it is: