gpt4 book ai didi

python - 带有正则表达式的 Ansible lineine 文件在不应该添加新行的情况下添加新行

转载 作者:行者123 更新时间:2023-11-30 22:54:41 25 4
gpt4 key购买 nike

我目前有这个用于配置 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 放入的新行?

最佳答案

问题是你也在匹配换行符。不要在匹配中包含换行符。这应该有效:

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

关于python - 带有正则表达式的 Ansible lineine 文件在不应该添加新行的情况下添加新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37682639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com