Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lineinfile: Don't insert lines if they already exist

It's creating a new file and adding content to it. If a re-run ansible for a second time the text content will be applied again below the lines but overwrite the last line bantime = 86400.

What I need it to do, is if the text already is applied, don't add it again. I assume my regexp is set wrong.

- name: add custom settings 
  lineinfile: dest=/etc/fail2ban/jail.local regexp='^' line='maxretry = 3\nfindtime = 10800\nbantime = 86400' create=yes state=present backrefs=yes
like image 487
nicoX Avatar asked Aug 11 '15 08:08

nicoX


People also ask

Does Ansible copy overwrite?

By default, the ansible copy module does a force copy to the destination and overwrites the existing file when present.

How do you check if a line exists in a file Ansible?

First, use "replace module" to detect if the line you are looking for is here and change it with the something else. (Like same line + something at the end). Then if "replace" is true, It means your line is here then replace the new line with a particularity, with the new line looking.

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.


1 Answers

From the lineinfile examples:

# Add a line to a file if it does not exist, without passing regexp
- lineinfile: dest=/tmp/testfile line="192.168.1.99 foo.lab.net foo"

Line with \n is not a line, those are multiple lines and they can't be matched on next run as a line. You should add each line as a separate task:

- name: add maxretry setting
  lineinfile: dest=/etc/fail2ban/jail.local line='maxretry = 3' create=yes

- name: add findtime setting
  lineinfile: dest=/etc/fail2ban/jail.local line='findtime = 10800' create=yes

- name: add bantime setting
  lineinfile: dest=/etc/fail2ban/jail.local line='bantime = 86400' create=yes

Also remove regexp and backerefs settings, since they are not needed and state, since present is a default value.


However it's better to also pass regexp with setting and the name without value. So if you change setting value, it will replace string in file instead of adding new one, like:

- name: add maxretry setting
  lineinfile: dest=/etc/fail2ban/jail.local regexp='^maxretry = ' line='maxretry = 3' create=yes
like image 143
Yaroslav Admin Avatar answered Nov 05 '22 10:11

Yaroslav Admin