Question:
In Ansible I’ve used register
to save the results of a task in the variable people
. Omitting the stuff I don’t need, it has this structure:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
{ "results": [ { "item": { "name": "Bob" }, "stdout": "male" }, { "item": { "name": "Thelma" }, "stdout": "female" } ] } |
I’d like to use a subsequent set_fact
task to generate a new variable with a dictionary like this:
1 2 3 4 5 |
{ "Bob": "male", "Thelma": "female" } |
I guess this might be possible but I’m going round in circles with no luck so far.
Answer:
I think I got there in the end.
The task is like this:
1 2 3 4 5 |
- name: Populate genders set_fact: genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}" with_items: "{{ people.results }}" |
It loops through each of the dicts (item
) in the people.results
array, each time creating a new dict like {Bob: "male"}
, and combine()
s that new dict in the genders
array, which ends up like:
1 2 3 4 5 |
{ "Bob": "male", "Thelma": "female" } |
It assumes the keys (the name
in this case) will be unique.
I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items
:
1 2 3 4 5 |
- name: Populate genders set_fact: genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}" with_items: "{{ people.results }}" |
This keeps combining the existing list with a list containing a single dict. We end up with a
genders
array like this:
1 2 3 4 5 |
[ {'name': 'Bob', 'gender': 'male'}, {'name': 'Thelma', 'gender': 'female'} ] |