I’m using Ansible and I need to replace a line in a file. The file is a logrotate configuration file for apache /etc/logrotate.d/apache2
. Before modification, the line reads
/var/log/apache2/*.log {
which I want to replace with
/var/log/apache2/*.log /var/log/apache2/*/*.log {
I’d rather not rewrite the whole file, not to affect the content of the configuration.
I can do this with the lineinfile
module:
- name: Configure logrotate for Apache
lineinfile:
dest: /etc/logrotate.d/apache2
regexp: '^(/var/log/apache2/\*\.log) (?:/var/log/apache2/\*/\*\.log )?{$'
# The backrefs option is required to ensure the line won’t just be
# added, breaking the syntax of the file…
backrefs: yes
line: '\1 /var/log/apache2/*/*.log {'
Unfortunately, this task succeeds (with no action) if the regexp is not matched in the configuration file. I’d rather have it fail.
The solution I found is to check the configuration with an extra task:
- name: Check logrotate’s configuration for Apache
command: egrep '^/var/log/apache2/\*\.log /var/log/apache2/\*/\*\.log {$' /etc/logrotate.d/apache2
changed_when: no
This seems to work, but I’m unhappy with the duplication of the regexp…
Is there a better way to change a line while failing if that line is not present?
Note that I’m currently stuck with (the quite ancient) Ansible 2.2, but I’m still interested by solutions that work with newer versions.
A: The task below does the job with lineinfile
A: The task below fails when pattern is not in the configuration file