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
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
With the accepted solution, even though you ignore errors, you will still get ugly red error output on the first task if there is no match:
If you want less verbose output, you can use
awk
instead ofgrep
.awk
won't return an error on a non-match, which means the first check task below won't error regardless of a match or non-match:Notice that my second task uses the match filter as awk returns the matched string if it finds a match.
The alternative above will produce the following output regardless of whether the check task has a match or not:
IMHO this is a better approach as you won't ignore other errors in your first task (e.g. if the specified file did not exist).
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.
Use ansible lineinfile command, but this command will update the file with the line if it does not exists.
Update 2017-08-28: Older Ansible versions need to use
always_run: yes
instead ofcheck_mode: no
.Another way is to use the "replace module" then "lineinfile module".
The algo is closed to the one used when you want to change the values of two variables.
Example:
With the same idea, you can do something if the lineSearched is here: