In ansible, I need to check whether a particular line present in a file or not. Basically, I need to convert the following command to an ansible task. My goal is to only check.
grep -Fxq "127.0.0.1" /tmp/my.conf
The Ansible lineinfile moduleAnsible lineinfile module is helpful when you want to add, remove, modify a single line in a file. You can also use conditions to match the line before modifying or removing using the regular expressions. You can reuse and modify the matched line using the back reference parameter.
You can use the lineinfile Ansible module to achieve that. The regexp option tells the module what will be the content to replace. The line option replaces the previously found content with the new content of your choice. The backrefs option guarantees that if the regexp does not match, the file will be left unchanged.
There is no Ansible grep module, but you can use the grep commands along with shell module or command module. We can store the results of the task and use it in various conditional statements, print them or use them for debugging purposes.
Use check_mode, register and failed_when in concert. This fails the task if the lineinfile module would make any changes to the file being checked. Check_mode ensures nothing will change even if it otherwise would.
- name: "Ensure /tmp/my.conf contains '127.0.0.1'" lineinfile: name: /tmp/my.conf line: "127.0.0.1" state: present check_mode: yes register: conf failed_when: (conf is changed) or (conf is failed)
- name: Check whether /tmp/my.conf contains "127.0.0.1" command: grep -Fxq "127.0.0.1" /tmp/my.conf register: checkmyconf check_mode: no ignore_errors: yes changed_when: no - name: Greet the world if /tmp/my.conf contains "127.0.0.1" debug: msg="Hello, world!" when: checkmyconf.rc == 0
Update 2017-08-28: Older Ansible versions need to use always_run: yes
instead of check_mode: no
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With