[英]regex ansible lineinfile subsection
我對ansible相當陌生,並且一直在使用shell腳本解決以下問題,但是我認為正確的方法是使用lineinfile
模塊,只是不確定如何做到這一點。
假設我有一個文件,其中包含以下文本。
<cpu>
<alarm>
active = yes
</alarm>
</cpu>
<disk>
<alarm>
active = yes
<fixed>
<#>
active = yes
description = File system /
<inode_error>
active = yes
threshold = 2
message = InodeError
</inode_error>
</#>
<#boot>
active = yes
description = File system /boot
percent = yes
<error>
active = yes
threshold = 5
message = DiskError
</error>
</#boot>
</fixed>
</alarm>
</disk>
我要確保正確設置以下部分。
<disk><alarm><fixed><#boot><error>"threshold = 2"</error></#boot></fixed></alarm></disk>
有沒有辦法只(修改/確保存在)該行,通常此文件更大,包含更多部分,但我刪除了一些內容,因此該問題可讀。
更新:修改它,因為它不是有效的XML,並且XML模塊將無法正確解析文件。
謝謝!
lineinfile
每行掃描文件,因此您無法為上下文定義定義復雜的多行正則表達式。
replace
模塊支持多行正則表達式。
如果文件中的threshold = X
,並且要確保將其設置為特定值,則可以使用此regexp:
- replace:
path: ./test.txt
regexp: '(<disk>[\s\S]*<alarm>[\s\S]*<#boot>[\s\S]*<error>[\s\S]*)(threshold\s*=\s*\d+)([\s\S]*?<\/error>)'
replace: '\1threshold = 2\3'
它在<disk>...<alarm>...<#boot>...<error>...
搜索線threshold\\s*=\\s*\\d+
。 該代碼是冪等的-因此,如果threshold = 2
,則什么也不做。
但是,如果沒有threshold = X
字符串,它將失敗。 您應該為這種情況構造更復雜的正則表達式。
您可以使用lineinfile模塊( http://docs.ansible.com/ansible/latest/lineinfile_module.html ),在其中可以編寫正則表達式來修改/添加行,並使用validate函數運行命令以確保xml文件具有正確的語法。
如果您使用的是Ansible 2.4,則可以使用xml模塊( https://docs.ansible.com/ansible/2.4/xml_module.html )並使用attribute參數來檢查是否已設置xml文件中的xpath,如下所示:
- name: Read attribute value
xml:
path: /foo/bar.xml
xpath: /business/website/validxhtml
content: attribute
attribute: validatedon
register: xmlresp
問候
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.