Jiri B
Jiri B

Reputation: 390

Filter out elements from list if matching multiple patterns

I need to filter out elements from a list if a list of patterns would be found in the element.

I'm able to do it for one pattern but I don't know how many patterns I would have in my 'exclude_patterns' list:

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

How to make it work if length of 'exclude_patterns' is dynamic, ie. not known in advance?

Using the patterns list itself in reject() causes:

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

Upvotes: 2

Views: 1995

Answers (1)

Zeitounator
Zeitounator

Reputation: 44605

match uses a regexp. Simply construct a regexp with all your possible matches with the | operator surrounded by parenthesis, e.g. (match1|match2)

In case of a single elements, the parenthesis will not harm, e.g. (singlematch)

Here is an example:

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

which gives:

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   

Upvotes: 2

Related Questions