问题
Variable mule_runtimes has a list of dictionaries:
- id: N-Newton
version: 4.3.0
- id: N-Galileo
version: 3.9.0-hf4
- id: N-Einstein
version: 3.8.5-hf4
I want the dictionary with id = N-Einstein.
I have tried using this:
- debug:
msg: "{{ mule_runtimes | selectattr('id', 'equalto', 'N-Einstein') | to_json }}"
And got error: Unexpected templating type error occurred on ({{ mule_runtimes | selectattr('id', 'equalto', 'N-Einstein') | to_json }}): Object of type 'generator' is not JSON serializable. What's the correct way to pick a dictionary from a list?
回答1:
The first problem is that mule_runtimes | selectattr('id', 'equalto', 'N-Einstein')
returns a generator. Think of it like d for d in mule_runtimes if d['id'] == 'N-Einstein'
in Python. You'll need to convert it to something JSON serializable (like a list) before using the to_json
filter.
The second problem is that it doesn't select only a single dictionary from the list. The predicate id == 'N-Einstein'
could be true for multiple dictionaries. If you know it will only match one dictionary, you'll need to convert the list to a single dictionary.
Putting that all together:
{{ mule_runtimes | selectattr('id', 'equalto', 'N-Einstein') | list | last | to_json }}
回答2:
I suggest json_query:
- name: dictionaries
vars:
mule_runtimes:
- id: N-Newton
version: 4.3.0
- id: N-Galileo
version: 3.9.0-hf4
- id: N-Einstein
version: 3.8.5-hf4
json: "{{ mule_runtimes }}"
query: "[?id=='{{ want }}'].version"
want: N-Einstein
debug:
msg: "{{ json | json_query(query) }}"
Gives the output:
TASK [test : dictionaries] *****************************************************
ok: [127.0.0.1] => {
"msg": [
"3.8.5-hf4"
]
}
来源:https://stackoverflow.com/questions/62313989/ansible-pick-dictionary-out-of-a-list-of-dictionaries