Question:
toy example
Essentially, I want to do something like:
1 2 |
['hello', 'apple', 'rare', 'trim', 'three'] | select(match('.*a[rp].*')) |
Which would yield:
1 2 |
['apple', 'rare'] |
what am I talking about?
The match
filter and select
filter. My issue arises from the fact that the select filter only supports unary “tests”.
I’m on Ansible 1.9.x.
my actual use case
…is closer to:
1 2 |
lookup('dig', ip_address, qtype="PTR", wantList=True) | select(match("mx\\..*\\.example\\.com")) |
So, I want to get all the PTR records associated with an IP and then filter out all the ones that don’t fit a given regex. I’d also want to ensure that there’s only one element in the resulting list, and output that element, but that’s a different concern.
Answer:
This design pattern worked for me:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
---- - hosts: localhost connection: local vars: my_list: ['hello', 'apple', 'rare', 'trim', "apropos", 'three'] my_pattern: 'a[rp].*' tasks: - set_fact: matches: "{%- set tmp = [] -%} {%- for elem in my_list | map('match', my_pattern) | list -%} {%- if elem -%} {{ tmp.append(my_list[loop.index - 1]) }} {%- endif -%} {%- endfor -%} {{ tmp }}" - debug: var: matches failed_when: "(matches | length) > 1" |