when: a file contains this regexp

Hi,

how can i execute a ansible task only if a file contains a specfic regexp ?
I was hoping to use the when: statement as follows :-

  • name: do this task only if file contains fred
    command: some command
    when: file contains “fred”

Can something like this work ? Thanks for any help.

Pete

I think what you’d want to do here is use the shell module to check for the regex with grep, emphasis on “I think”. You could also use the exit code, since grep exits with a 0 when it matches lines, 1 if no match is found. This is probably easier.

  • name: Check if file has Fred
    shell: grep ‘fred’ /path/to/file
    register: grep

  • name: Do this if we find Fred
    debug: msg=“We found Fred”
    when: grep.stdout

You could also use the “slurp” module, and register the full file contents, and use

when: foo.contents | match(regexp)

I think Paul’s suggestion is clearer and easier though, and transfers less over the wire.

Could also just use the rc from grep vs stdout, I think.

Also don’t forget to add the “ignore_errors: yes” parameter, otherwise your play will just exit in error if the string isn’t found.