Ansible jinja2 过滤器拒绝

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

我想从信息中拒绝/排除 xyz

    "info": [
        {
            "effect": {
                "com": "both",
                "policy": {
                    "name": "auto"
                },
                "schedule": "-",
                "state": "enabled"
            },
            "name": "test_inline",
            "abc": {
                "name": "svm1",
                "xyz": "56a0599f"
            },
            "xyz": "42d6-56a0599f"
        }
    ]

set_fact:
    info : "{{ info | default ([]) + facts | json_query('response.records') | reject('equalto','xyz') }}"
tried reject('match', '[xyz]')

但是 xyz 仍然没有被排除在信息之外。

ansible jinja2
1个回答
0
投票

根据您想要实现的目标,一个最小示例剧本

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:

    info: [
        {
            "effect": {
                "com": "both",
                "policy": {
                    "name": "auto"
                },
                "schedule": "-",
                "state": "enabled"
            },
            "name": "test_inline",
            "abc": {
                "name": "svm1",
                "xyz": "56abcdef"
            },
            "xyz": "1234-56abcdef"
        }
    ]

  tasks:

  - debug:
      msg: "{{ info | first | dict2items | rejectattr('key', 'eq', 'xyz') | list | items2dict }}"

  - debug:
      msg: "{{ info | combine({'xyz': omit}) }}"

将产生

的输出
TASK [debug] ********
ok: [localhost] =>
  msg:
    abc:
      name: svm1
      xyz: 56abcdef
    effect:
      com: both
      policy:
        name: auto
      schedule: '-'
      state: enabled
    name: test_inline

对于所有出现的键

xyz
,您可能需要采用
remove_keys
过滤器 – 递归地从数据中删除特定键
。它适用于字典和列表。

  - debug:
      msg: "{{ info | first | ansible.utils.remove_keys(target='xyz') }}"

  - debug:
      msg: "{{ info | ansible.utils.remove_keys(target='xyz') }}"

产生

的输出
TASK [debug] *********
ok: [localhost] =>
  msg:
  - abc:
      name: svm1
    effect:
      com: both
      policy:
        name: auto
      schedule: '-'
      state: enabled
    name: test_inline

致谢

© www.soinside.com 2019 - 2024. All rights reserved.