Search code examples
searchansiblefull-text-searchstring-matchingcase-when

How to search for a string in a file using Ansible when condition


I have a list of search string separated by '\n' in a variable listofips

I wish to search for the string in a file hello.csv which is under my playbook_dir

I may be having some syntax issue which I'm not sure but below is what I tried.

- set_fact:
    listofips: '10.0.0.1\n10.0.0.2\n10.0.0.3'

- set_fact:
    foundips: "{{ foundips + item + ', ' }}"
  when: lookup('file', "{{ playbook_dir }}/hello.csv").splitlines() | select('match', "{{ item }}") | list
  loop: "{{ listofips.split('\n') }}"

Unfortunately, the search string exists in the file but ansible when condition fails to match.

I would also know if it is possible to have both the exact match or a wild card match?

Can you please suggest ?


Solution

  • there are a couple of issues to check:

    a. foundips: "{{ foundips + item + ', ' }}"

    in the first run where the condition will be true, the foundips is not initialized, and will error. you should use:

    foundips: "{{ foundips|default([]) + [item] }}"
    

    b. the select filter should use this pattern for search:

    select('match', '.*' + item + '.*')
    

    c. the when condition is not properly set. you convert to a list but then to make sure you have results you need to check if the list has length > 0:

    when: lookup('file', "{{ playbook_dir }}/hello.csv").splitlines() | select('match', '.*' + item + '.*') | list | length > 0
    

    d. if you use a simple debug task to see if the split('\n') works as expected you will realise its not, you need to use double backward slash:

    loop: "{{ listofips.split('\\n') }}"
    

    to summarize, please try this task:

      - set_fact:
          foundips: "{{ foundips|default([]) + [item] }}"
        when: lookup('file', "{{ playbook_dir }}/hello.csv").splitlines() | select('match', '.*' + item + '.*') | list | length > 0
        loop: "{{ listofips.split('\\n') }}"
    

    cheers