使用lineinfile插入行但未按预期工作

问题描述

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

/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
}

我想在compress之后添加delaycompressmissingok。这是我的代码:

- 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

但是将它们都添加到文件末尾(最后几行)。
注意:我在compressdelaycompress之前添加了4个空格。

解决方法

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

由于您在missingoksharedscripts之前确实有空格,因此您的insertafterinsertbefore正则表达式are matching nothing

要解决此问题,您可以借助\s来允许空格和空格,而*可以匹配任何空格,制表符或换行符,而星号^\s*missingok 则可以匹配零或更多连续字符。

因此正确的正则表达式将是

  • ^\s*sharedscripts
    
    Test it here
  • - 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
    

针对您的任务的解决方法是:

UTC[2]

请注意,因为Ansible是Python应用程序,backslashes \ have a special meaning and have to be escaped

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...