2

我正在使用lineinfile在系统日志文件中插入行。这是我的系统日志:

/var/log/cron
/var/log/maillog
/var/log/messages
/var/log/secure
/var/log/spooler
{
    missingok
    sharedscripts
    postrotate
        /bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true
    endscript
}

我想compressdelaycompress. missingok这是我的代码:

- name: "Adding compress line in /etc/logrotate.d/syslog"
  lineinfile:
    path: /etc/logrotate.d/syslog
    insertafter: "^missingok"
    line: "    compress"
    firstmatch: yes
    state: present

- name: "Adding delaycompress line in /etc/logrotate.d/syslog"
  lineinfile:
    path: /etc/logrotate.d/syslog
    insertbefore: "^sharedscripts"
    line: "    delaycompress"
    firstmatch: yes
    state: present

但是它在文件的末尾添加了两者(在最后几行)。
注意:我在compressand之前添加了 4 个空格delaycompress

4

1 回答 1

2

发生这种情况是因为插入符号^在正则表达式中匹配字符串的开头而不消耗任何字符。

missingok并且因为您在and之前确实有空格sharedscripts,所以您的insertafterinsertbefore正则表达式不匹配任何内容

\s要解决此问题,您可以在与任何空格、制表符或换行符匹配的字符以及*匹配零个或多个连续字符的星号的帮助下仅在行的开头允许空格和空格。

所以正确的正则表达式是

您的任务的解决方法是:

- name: "Adding compress line in /etc/logrotate.d/syslog"
  lineinfile:
    path: /etc/logrotate.d/syslog
    insertafter: "^\\s*missingok"
    line: "    compress"
    firstmatch: yes
    state: present

- name: "Adding delaycompress line in /etc/logrotate.d/syslog"
  lineinfile:
    path: /etc/logrotate.d/syslog
    insertbefore: "^\\s*sharedscripts"
    line: "    delaycompress"
    firstmatch: yes
    state: present

请注意,由于 Ansible 是 Python 应用程序,因此反斜杠\具有特殊含义,必须进行转义

于 2020-08-10T20:47:25.033 回答