Ansible 从字典列表中选择字典 [英] Ansible pick dictionary out of a list of dictionaries

查看:37
本文介绍了Ansible 从字典列表中选择字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

变量 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') 返回一个生成器.把它想象成 d for d in mule_runtimes if d['id'] == 'N-Einstein' 在 Python 中.在使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆