Ansible find in path exact filename without regex

Issue

Using Ansible I am struggling to use the find module for an exact filename without using regex.

My use case takes user input and I am worried that the user would try to be clever and use regex to do more than I want to allow them to do. I could reject the string if it contains regex characters, but I would rather treat the string as an exact filename.

The code below does find matching files, but if the filename given is *.txt, all .txt files will be matched.

- name: collect paths for matching file
  find:
    paths: "{{ target_folder }}"
    patterns: "{{ filename }}"
    file_type: file
    recurse: true
  register: file_matches

The reason I am worried about the impact of rejecting particular strings is that I know that, in rare cases, some of the filenames that are going to be looked at have non-ASCII characters, and I don’t know how that will play with a no-regex assert.

Solution

As counter-intuitive as it seems, an option is to actually enable a match via regex, with the parameter use_regex: true in combination with the usage of the regex_escape filter.

The reason for this is pointed in the pattern parameter comment:

One or more (shell or regex) patterns, which type is controlled by use_regex option.

Source: https://docs.ansible.com/ansible/latest/collections/ansible/builtin/find_module.html#parameter-patterns

And since the default of use_regex is false, the default behaviour would be to have a Shell pattern, which won’t work well if you escape the character in a regex fashion.

So, you task ends up being:

- name: collect paths for matching file
  find:
    paths: "{{ target_folder }}"
    patterns: "{{ filename | regex_escape }}"
    file_type: file
    recurse: true
    use_regex: true
  register: file_matches

Answered By – β.εηοιτ.βε

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published