2016-06-07 11 views
0

我現在有這個文件配置的Nagios NRPE:用正則表達式Ansible lineine文件添加新線時,它不應該

/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命令,無論工作

我試圖使用ansible的lineinfile模塊,讓我到另一個變量添加到開頭的行only_from

目前我有以下提供的IP)的:

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

而且它按預期工作。我該如何擺脫這個可靠的新線路?

+0

的字符串是最有可能的'192.168.1.1 \ N'。查看是否有任何方法去除新行並將其附加到字符串的整個末尾。你可能仍然需要在所有這些結束時換行,但不是在中間。就像'192.168.1.1 127.0.0.1 \ n'我假設? – idjaw

+0

@idjaw你是對的,我確實希望在最後有新的一行。你對將\ n添加到backref(我的regex,ansible,python)有什麼想法嗎? – Mitch

+0

不幸的是,我還沒有玩過這個模塊。在這一點上,我將不得不像你一樣嘗試。 – idjaw

回答

2

問題是你也在匹配換行符。不要在比賽中包含換行符。這應該工作:

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 
>>> 
相關問題