Ansible playbook to insert a line if specific line not present

Viewed 65

I'm trying to modify a logrotate file on multiple servers. When the line "noolddir" is not present in a block in the file, the line should be added. I wrote this playbook:

- name: Update logrotate files on servers
  hosts: all
  tasks:
  - name: change myapplication
    ansible.builtin.replace:
      path: /etc/logrotate.d/myapplication
      regexp:  '(?:noolddir\n)?(rotate 30)$'
      replace: '    noolddir\n\1'

but, it is not working.
The logrotate file I need to edit looks like this:

/opt/appvendor/log//myapplication_*.log {
    daily
    rotate 30
    compress
    missingok
    notifempty
    su root appvendor
    dateext
    postrotate
        /bin/systemctl reload httpd.service > /dev/null 2>/dev/null || true
    endscript
    }

/opt/otherapplication/instances/*/*/otherapplication/logs/*.log
/opt/otherapplication/instances/*/somefolder/*/*/logs/*.log {
    daily
    noolddir
    rotate 30
    compress
    missingok
    notifempty
    copytruncate
    su root appvendor
}

The result should be:

/opt/appvendor/log//myapplication_*.log {
    daily
    noolddir
    rotate 30
    compress
    missingok
    notifempty
    su root appvendor
    dateext
    postrotate
        /bin/systemctl reload httpd.service > /dev/null 2>/dev/null || true
    endscript
    }

/opt/otherapplication/instances/*/*/otherapplication/logs/*.log
/opt/otherapplication/instances/*/somefolder/*/*/logs/*.log {
    daily
    noolddir
    rotate 30
    compress
    missingok
    notifempty
    copytruncate
    su root appvendor
}

However when I run the playbook, nothing is changed.
Any suggestions?

1 Answers

Maybe this answer isn't the most optimal one, but I hope it helps.

The Idea is to search for both rotate 30 and noolddir\n rotate 30 and replace them.
I am not experienced with regex, but tried my best, see https://regex101.com/r/YPnlM3/1.

That means for the playbook to do its job, every block in file should have rotate 30

- name: Update logrotate files on servers
  hosts: all
  tasks:
  - name: change myapplication
    ansible.builtin.replace:
      path: /etc/logrotate.d/myapplication
      regexp:  'noolddir\n.*rotate 30$|\.*rotate 30$'
      replace: 'noolddir\n    rotate 30'
Related