i needed to adjust local log retention period on bunch of servers. rules:
- touch only logs which have daily or weekly rotation period,
- if it’s shorter than ~1 month – change it to 30 days
- otherwise – don’t change anything
with some help from chatgpt and grog3 i’ve cobbled this one:
- name: Ensure all logrotate configs with 'daily' have 'rotate 30'
hosts: all
tasks:
- name: Find files containing 'daily' in /etc/logrotate.d
ansible.builtin.find:
paths: /etc/logrotate.d
patterns: '*'
contains: '.*(daily).*'
register: find_daily
- name: Find files with low value for rate in /etc/logrotate.d for daily
ansible.builtin.find:
paths: /etc/logrotate.d
patterns: '*'
contains: '^\s*rotate ([0-9]|[1-2][0-9])\s*$'
register: find_low_retention_daily
- name: Set rotate to 30 in matched files
ansible.builtin.lineinfile:
path: "{{ item }}"
regexp: '^(\s*)rotate\s+\d+'
line: ' rotate 30'
backrefs: yes
# if i used 'find_low_retention_daily | intersect(find_daily)' - it would work unreliabely, probably due to difference in atime
loop: "{{ (find_low_retention_daily.files|map(attribute='path') |list ) | intersect( find_daily.files|map(attribute='path') |list ) }}"
- name: Find files containing 'weekly' in /etc/logrotate.d
ansible.builtin.find:
paths: /etc/logrotate.d
patterns: '*'
contains: '.*(weekly).*'
register: find_weekly
- name: Find files with low value for rate in /etc/logrotate.d for weekly
ansible.builtin.find:
paths: /etc/logrotate.d
patterns: '*'
contains: '^\s*rotate ([1-4])\s*$'
register: find_low_retention_weekly
- name: Set rotate to 30 in matched files
ansible.builtin.lineinfile:
path: "{{ item }}"
regexp: '^(\s*)rotate\s+\d+'
line: ' rotate 5'
backrefs: yes
loop: "{{ (find_low_retention_weekly.files|map(attribute='path') |list ) | intersect( find_weekly.files|map(attribute='path') |list ) }}"
# some debug info
# - name: files in find_daily
# ansible.builtin.debug:
# msg: "File found: {{ item }}"
# loop: "{{ find_daily.files }}"