如果匹配多个模式,则从列表中滤除元素

时间:2020-07-02 16:32:59

标签: ansible

如果需要在元素中找到模式列表,则需要从列表中过滤掉元素。

我能够针对一种模式进行处理,但我不知道我的“ exclude_patterns”列表中将包含多少种模式:

- name: test
  hosts: localhost
  gather_facts: false
  become: false
  vars:
    lines:
      - foo
      - bar
      - UUID
    exclude_patterns:
      - UUID

  tasks:

    - debug:
        msg: "{{ lines | reject('match', exclude_patterns[0]) | list }}"

如果'exclude_patterns'的长度是动态的,即如何使它起作用。事先不知道吗?

在reject()中使用模式列表本身会导致:

fatal: [localhost]: FAILED! => {
    "msg": "Unexpected templating type error occurred on ({{ lines | reject('match', exclude_patterns) | list }}): unhashable type: 'list'"
}

1 个答案:

答案 0 :(得分:0)

match使用正则表达式。只需用|运算符(用括号括起来)构造一个正则表达式,其中包含所有可能的匹配项,例如(match1|match2)

在单个元素的情况下,括号不会造成损害,例如(singlematch)

这里是一个例子:

---
- name: test
  hosts: localhost
  gather_facts: false
  become: false
  vars:
    lines:
      - foo
      - bar
      - UUID
      - toto
      - pipo
      - bingo
    exclude_patterns:
      - UUID
      - pipo
      - bar

  tasks:

    - debug:
        msg: "{{ lines | reject('match', '(' + exclude_patterns | join('|') + ')') | list }}"

给出:

PLAY [test] ****************************************************************************************************************************************************************************************************************************

TASK [debug] ***************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": [
        "foo",
        "toto",
        "bingo"
    ]
}

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