Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select regex matches in jinja2?

toy example

Essentially, I want to do something like:

['hello', 'apple', 'rare', 'trim', 'three'] | select(match('.*a[rp].*'))

Which would yield:

['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:

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.

like image 201
Parthian Shot Avatar asked Aug 05 '16 18:08

Parthian Shot


1 Answers

I found the following trick if you want to filter a list in Ansible (get the list with null values and make difference with null list) :

---
- hosts: localhost
  connection: local
  vars:
    regexp: '.*a[rp].*'
    empty: [null]
  tasks:
    - set_fact: matches="{{ ['hello', 'apple', 'rare', 'trim', 'three'] | map('regex_search',regexp)  | list|difference(empty) }}"
    - debug: msg="{{ matches }}"

Here is the output :

ok: [localhost] => {
    "msg": [
        "apple", 
        "rare"
    ]
}
like image 141
MVCaraiman Avatar answered Oct 14 '22 18:10

MVCaraiman