在 Ansible 的字典列表中搜索键 [英] Searching for key in a list of dicts in Ansible
问题描述
我有一个类似于以下内容的字典列表:
子网":[{"name": "subnet1-name34554",地址":192.168.1.100"id:"id1},{"name": "subnet2-name67678",地址":192.168.1.200"id":id2"},{"name": "subnet3-name23345",地址":192.168.1.300"id":id3"}]
我正在尝试使用部分名称搜索字典并返回全名.例如使用 subnet1
搜索应该返回 subnet1-name34554
如果我这样做:
- 名称:测试调试: msg="{{ 子网 | selectattr("name", "search", "subnet1") | list }}"
我得到一个带有单个 dict 的列表:
<预><代码> [{"name": "subnet1-name34554",地址":192.168.1.100"id:"id1}]我不确定下一步只提取名称"键是什么,或者是否有更好的方法?
结果你得到了 dicts 列表(单个 dict).
因此将其输入 first
过滤器以仅获取第一个元素,然后处理 name
属性.
- 名称:测试调试:msg: "{{ (subnets | selectattr('name', 'search', 'subnet1') | list | first).name }}"
I've got a list of dictionary that looks similar to the following:
"subnets": [
{
"name": "subnet1-name34554",
"address": "192.168.1.100"
"id: "id1"
},
{
"name": "subnet2-name67678",
"addr": "192.168.1.200"
"id": "id2"
},
{
"name": "subnet3-name23345",
"addr": "192.168.1.300"
"id": "id3"
}
]
I'm trying to search the dicts with a partial name and return the full name. E.g searching with subnet1
should return subnet1-name34554
If I do something like:
- name: test
debug: msg="{{ subnets | selectattr("name", "search", "subnet1") | list }}"
I get a list with a single dict back:
[
{
"name": "subnet1-name34554",
"address": "192.168.1.100"
"id: "id1"
}
]
I'm unsure what the next step to pull just the "name" key is, or if there is a better approach?
You get list of dicts (single dict) as a result.
So feed it into first
filter to get only first element and then address name
property.
- name: test
debug:
msg: "{{ (subnets | selectattr('name', 'search', 'subnet1') | list | first).name }}"
这篇关于在 Ansible 的字典列表中搜索键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!