如何解决使用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
之后添加delaycompress
和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
但是将它们都添加到文件末尾(最后几行)。
注意:我在compress
和delaycompress
之前添加了4个空格。
解决方法
之所以发生这种情况,是因为正则表达式中的插入符号^
匹配字符串的开头而不消耗任何字符。
由于您在missingok
和sharedscripts
之前确实有空格,因此您的insertafter
和insertbefore
正则表达式are matching nothing。
要解决此问题,您可以借助\s
来允许空格和空格,而*
可以匹配任何空格,制表符或换行符,而星号^\s*missingok
则可以匹配零或更多连续字符。
因此正确的正则表达式将是
-
Test it here^\s*sharedscripts
-
- 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。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。