Ansible从词典列表中选择词典
变量mule_运行时有一个字典列表:Ansible从词典列表中选择词典,ansible,Ansible,变量mule_运行时有一个字典列表: - 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的字典 我试过使用这个: - debug: msg: "{{ mule_runtimes | selectattr('id', 'equalto', 'N-Einstein') | to_json }}"
- 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的字典
我试过使用这个:
- debug:
msg: "{{ mule_runtimes | selectattr('id', 'equalto', 'N-Einstein') | to_json }}"
并获得错误:({mule_运行时| selectattr('id',equalto',N-Einstein')| to_json}})上发生意外的模板类型错误:“'generator'类型的对象不可json序列化。
从列表中选择词典的正确方法是什么?第一个问题是
mule\u运行时| selectattr('id','equalto','N-Einstein')
返回一个生成器。如果在Python中d['id']='N-Einstein',可以将其想象为mule_运行时中d的d。在使用to_JSON
过滤器之前,您需要将其转换为JSON可序列化的内容(如列表)
第二个问题是它没有从列表中只选择一个字典。谓词id=='N-Einstein'
对于多个字典可能为真。如果您知道它只匹配一个字典,则需要将列表转换为单个字典
综上所述:
{{ mule_runtimes | selectattr('id', 'equalto', 'N-Einstein') | list | last | to_json }}
我建议您进行以下查询:
- 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) }}"
给出输出:
TASK[测试:字典]***************************************************************************************************************************
确定:[127.0.0.1]=>{
“味精”:[
“3.8.5-hf4”
]
}