词典列表中的Ansible选择字典 [英] Ansible pick dictionary out of a list of dictionaries
问题描述
可变的mule_runtimes具有字典列表:
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
我想要id = N-Einstein的字典.
I want the dictionary with id = N-Einstein.
我尝试使用此功能:
- debug:
msg: "{{ mule_runtimes | selectattr('id', 'equalto', 'N-Einstein') | to_json }}"
并得到错误:({{mule_runtimes | selectattr('id','equalto','N-Einstein')| to_json}})发生意外的模板类型错误:类型为'generator'的对象不是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?
推荐答案
第一个问题是 mule_runtimes |selectattr('id','equalto','N-Einstein')
返回一个生成器.如果在python中,如果d ['id'] =='N-Einstein',则将其视为在mule_runtimes中对d的 d.在使用
to_json
过滤器之前,您需要将其转换为可序列化的JSON(例如列表).
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.
第二个问题是它不会从列表中仅选择单个词典.谓词 id =='N-Einstein'
对于多个词典而言可能是正确的.如果您知道它只会与一本字典匹配,则需要将列表转换为一本字典.
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.
将它们放在一起:
{{ mule_runtimes | selectattr('id', 'equalto', 'N-Einstein') | list | last | to_json }}
这篇关于词典列表中的Ansible选择字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!