Home > OS >  Filter list in ansible with a string (from variable)
Filter list in ansible with a string (from variable)

Time:07-28

I have a list in ansible for which I want to apply a filter with variable (string).

Here is the list example

ok: [localhost] => {
    "list1": [
        "aXYZb",
        "bbbb",
        "ccccXYZdsasd"
    ]
}

variable is a match with XYZ, and I want to filter the list with it to get

aXYZb
ccccXYZdsasd

I tried with union, but this works only in case string in the list is exact as the variable (it works for XYZ, not for aXYZb).

I'm also trying to filter it with regexp that use this variable for search, but something is not right. Here is what I tried:

- name: Filter a list with variable
  set_fact:
    list2: "{{ list1 | regex_search('variable1') }}"
  loop: "{{ list1 }}"
  loop_control:
    loop_var: item5

or the other way:

list2: "{{ list1 | map('regex_search',some_regular_expression_with_variable) | list }}"

This is not getting me expected result.

Does anyone knows how to achieve this, either with union, regex or maybe some other filtering solution)?

Thanks.

Here is an answer for Vladimir

Hi, I figured out why it's not working in my case. The thing is that for my var1 (which is I.E. abcdef), it cannot find the match for it because in the list I have strings like abcXYZdef. That is why union didn't work and also select from Vladimir. I believe we need to add REGEXP that checks only for particular characters (I know exactly which one). The REGEXP I used for extracting XYZ (in the task before this one) where:

'regex_replace', '(?:^.*(?=.{7})|\\d )', '')

and/or

'regex_search', '\\D(?=.{0,6}$)'

so I guess I need to add one of these, but the the question is where and how to combine it in this select? Maybe something like this:

list2: "{{ list1| select('search', REGEXP) | select ('search, var1) }}"  

CodePudding user response:

Given the list1 and var1

    list1: [aXYZb, bbbb, ccccXYZdsasd]
    var1: XYZ

Q: "The variable is a match with XYZ. Filter the list with it to get list2."

list2: [aXYZb, ccccXYZdsasd]

A: Use the test search. For example,

list2: "{{ list1|select('search', var1) }}"

Example of a complete playbook

- hosts: localhost
  vars:
    list1: [aXYZb, bbbb, ccccXYZdsasd]
    var1: XYZ
    list2: "{{ list1|select('search', var1) }}"
  tasks:
    - debug:
        var: list2
  • Related