在Ansible中的字典列表中搜索键 [英] Searching for key in a list of dicts in Ansible

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

问题描述

我有一个类似于以下内容的字典列表:

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"
        }
    ]

我正在尝试使用部分名称搜索字典并返回全名.例如,用subnet1搜索应返回subnet1-name34554

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

如果我做类似的事情:

- 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.

因此将其输入到first过滤器中,以仅获取第一个元素,然后访问name属性.

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屋!

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