Ansible - 从列表中删除空元素

问题描述 投票:0回答:2

我有一个 ansible 输出,我想从中删除特定属性的所有空(无)元素。这是示例列表:

"resources": [
    {
        "id": "9c40900909",
        "name": "some_name1"
    },
    {
        "id": "pc4b09090"
    },
    {
        "id": "8lknkkn45"
    },
    {
        "id": "9df40900909",
        "name": "some_name2"
    }
]

以下是我如何将列表减少为仅具有属性“名称”的“资源”:

- set_fact:
    resources_names: "{{ output.resources | map(attribute='name') }}"

问题是我得到的元素没有任何名称值。这些是以下输出中的“AnsibleUndefined”:

- debug:
    msg: resources_names list is "{{ resources_names }}"
ok: [localhost] => {
   "msg": "resources_names list is \"['some_name1', AnsibleUndefined, AnsibleUndefined, 'some_name2']\""
}

我尝试使用拒绝和正则表达式删除它,但这不起作用。

- set_fact:
    list2: "{{ resources_names | reject('match', '^$') | list }}"

与此相同:

- set_fact:
    resources_names: "{{ output.resources | map(attribute='name') | rejectattr('name', 'none') }}"

有什么想法吗?

谢谢。

list ansible element
2个回答
4
投票

简而言之:

---
- hosts: localhost
  gather_facts: false

  vars:
    resources: [
        {
            "id": "9c40900909",
            "name": "some_name1"
        },
        {
            "id": "pc4b09090"
        },
        {
            "id": "8lknkkn45"
        },
        {
            "id": "9df40900909",
            "name": "some_name2"
        }
    ]

  tasks:
    - debug:
        msg: "{{ resources | selectattr('name', 'defined') | map(attribute='name') }}"

给出:

$ ansible-playbook /tmp/play.yml 
[WARNING]: No inventory was parsed, only implicit localhost is available

PLAY [localhost] *******************************************************************************************************************************************************************************

TASK [debug] ***********************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": [
        "some_name1",
        "some_name2"
    ]
}

PLAY RECAP *************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

3
投票

使用过滤器json_query。此过滤器忽略缺失的属性

resources_names: "{{ output.resources|json_query('[].name') }}"

给予

resources_names:
  - some_name1
  - some_name2
© www.soinside.com 2019 - 2024. All rights reserved.