我目前有这个文件用于配置nagios nrpe:
/etc/xinetd.d/nrpe:
# default: on
# description: NRPE (Nagios Remote Plugin Executor)
service nrpe
{
flags = REUSE
socket_type = stream
port = 5666
wait = no
user = nagios
group = nagios
server = /usr/local/nagios/bin/nrpe
server_args = -c /usr/local/nagios/etc/nrpe.cfg --inetd
log_on_failure += USERID
disable = no
only_from = 192.168.1.1
}
(请注意,only_from是假IP,但我试图将ansible命令写入工作而不管提供的IP)
我尝试使用ansible的lineinfile模块,允许我将另一个变量添加到以only_from
开头的行
目前我有以下内容:
---
- name: Edit Existing | Edit xinetd.d/nrpe file
vars:
- nagios_ip: 194.54.46.12
lineinefile:
backrefs: yes
backup: yes
dest: /etc/xinetd.d/nrpe
line: 'only_from = \1 {{ nagios_ip }}'
regexp: '\s*only_from\s+=\s*(((\d{1,3}\.){3}\d{1,3}\s*)*)'
这主要是有效的。我改变了行,但是{{ nagios_ip }}
变量被发送到换行符,文件最终看起来像新行上的新IP地址,而不是在同一行:
# default: on
# description: NRPE (Nagios Remote Plugin Executor)
service nrpe
{
flags = REUSE
socket_type = stream
port = 5666
wait = no
user = nagios
group = nagios
server = /usr/local/nagios/bin/nrpe
server_args = -c /usr/local/nagios/etc/nrpe.cfg --inetd
log_on_failure += USERID
disable = no
only_from = 192.168.1.1
127.0.0.1
}
因为ansible / lineinfile使用python的正则表达式引擎我在普通的python中测试过它:
>>> s = ' only_from = 127.0.0.1'
>>> r = '\s*only_from\s+=\s*(((\d{1,3}\.){3}\d{1,3}\s*)*)'
>>> import re
>>> re.match(r,s).group(1)
'127.0.0.1'
>>> re.match(r,s).group(1) + ' 192.168.1.1'
'127.0.0.1 192.168.1.1'
>>>
它按预期工作。如何摆脱ansible投入的新线?
答案 0 :(得分:3)
问题是你也在匹配换行符。不要在比赛中包含换行符。这应该有效:
regexp: '\s*only_from\s+=\s*((\d{1,3}\.){3}\d{1,3})\s*'
为什么你的普通python有效?因为您在测试中方便地省略了换行符。您的测试字符串应为:
s = ' only_from = 127.0.0.1\n'
您更正后的示例是:
>>> s = ' only_from = 127.0.0.1\n'
>>> r = '\s*only_from\s+=\s*(((\d{1,3}\.){3}\d{1,3}\s*)*)'
>>> import re
>>> print re.match(r,s).group(1) + ' 192.168.1.1'
127.0.0.1
192.168.1.1
>>> r = '\s*only_from\s+=\s*((\d{1,3}\.){3}\d{1,3})\s*'
>>> print re.match(r,s).group(1) + ' 192.168.1.1'
127.0.0.1 192.168.1.1
>>>