What's the safest way to do grep-like searches in files?

HI,
I need to do a grep-like search in a file without using shell commands and in a check_mode compatible way.
I just need to check the presence of a given string a in a file without doing overwrites of any kind.
I implemented something with lineinfile but I’m very annoyed by the need to specify the line parameter to overwrite the file
because the r.e. may be wrong.

Is there any cleaner way to do what I need?

  • name: grub
    become: true
    lineinfile:
    path: /etc/myfile
    backrefs: yes
    regexp: “^CMDLINE (.*)”
    line: ‘CMDLINE \1’
    state: present
    register: myxx

Thanks.

You should run your playbook in check mode until you’re certain that your regular expression is precise.

I would honestly use slurp to fetch the file and maybe a set_fact to set a var indicating it’s existence. That is the pattern I have always used. Something like:

  • slurp:
    path: /etc/myfile
    register: myfile

  • set_fact:
    contains_cmdline: “{{ myfile.contents|b64decode|search(”^CMDLINE") }}"

I like it. Thanks

That may turn out to be too late depending on the complexity of the R.E.
It’s not an error-proof approach.

The find module has a 'contains' option.

Not knowing the state of your environment or what you intend to do with the registered fact, I can only offer you this advice:

If a line in a file needs to exist and an action should occur if that file is changed, line in file is the most precise way to do this operation.

If you are using searches or other methods to find values in a file in order to notify actions, you haven’t added additional precision to your plays. The risk of using regular expression is no different if you use line in file or if you use grep. There’s some great regular expression builders on the web. Try using that to improve the precision of lineinfile, instead of querying system states using grep or other utilities.