when: a file contains this regexp

6,649 views
Skip to first unread message

Peter Leggett

unread,
May 1, 2014, 10:11:19 AM5/1/14
to ansible...@googlegroups.com
 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

Paul Durivage

unread,
May 1, 2014, 4:27:20 PM5/1/14
to ansible...@googlegroups.com
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 received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To post to this group, send email to ansible...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/cd6273a1-3a1b-45c0-b6c9-54dcd4e7fa84%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Michael DeHaan

unread,
May 1, 2014, 5:33:34 PM5/1/14
to ansible...@googlegroups.com
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.




Michael DeHaan

unread,
May 1, 2014, 5:33:50 PM5/1/14
to ansible...@googlegroups.com
Could also just use the rc from grep vs stdout, I think.


kevin wessel

unread,
Oct 8, 2015, 8:38:53 PM10/8/15
to Ansible Project, p.f.l...@gmail.com
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.
Reply all
Reply to author
Forward
0 new messages