Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only check whether a line present in a file (ansible)

Tags:

ansible

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 
like image 419
Ansuman Bebarta Avatar asked Jun 11 '15 16:06

Ansuman Bebarta


People also ask

What is line in file in Ansible?

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.

How do you replace a line in a file using Ansible?

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.

How do you grep Ansible output?

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.


2 Answers

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) 
like image 71
LHSnow Avatar answered Sep 21 '22 15:09

LHSnow


- 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.

like image 20
Antonis Christofides Avatar answered Sep 17 '22 15:09

Antonis Christofides