正则表达式 ansible lineinfile 小节 [英] regex ansible lineinfile subsection

查看:30
本文介绍了正则表达式 ansible lineinfile 小节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 ansible 还很陌生,并且一直在使用 shell 脚本解决以下问题,但我认为正确的方法是使用 lineinfile 模块,只是不确定如何完成此操作.

I am fairly new to ansible and have been solving the following problem with a shell script, but the proper way I believe is to use the lineinfile module, just not sure how to accomplish this.

假设我有一个包含以下文本的文件.

Let's say I have a file with the following text in it.

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

我想确保以下部分设置正确.

I want to make sure the following section is set correctly.

<disk><alarm><fixed><#boot><error>"threshold = 2"</error></#boot></fixed></alarm></disk>

有没有办法只(修改/确保存在)那一行,通常这个文件更大,有更多的部分,但我删除了一些,所以问题是可读的.

is there a way to only (modify/make sure exists) that line, normally this file is much larger with many more sections, but I erased some so the question is readable.

更新:修改它,因为它不是有效的 XML,并且 XML 模块将无法正确解析文件.

Update: Modifying this as it is not valid XML and the XML module will not parse the file correctly.

谢谢!

推荐答案

lineinfile 每行扫描文件,因此您不能为上下文定义定义复杂的多行正则表达式.

lineinfile scans file per line, so you can't define complex multiline regexp for context definition.

replace 模块支持多行正则表达式.

replace module support multiline regexp.

如果您在文件中有 threshold = X 并希望确保将其设置为特定值,则可以使用此正则表达式:

If you have threshold = X in the file and want to be sure it is set to specific value, you can use this 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'

它在 ......<#boot>... 中搜索行 threshold\s*=\s*\d+<错误>....这段代码是幂等的——所以如果 threshold = 2,那么什么都不做.

It searches for line threshold\s*=\s*\d+ inside <disk>...<alarm>...<#boot>...<error>.... This code is idempotent – so if threshold = 2, then nothing is done.

但是如果没有threshold = X字符串,就会失败.您应该为这种情况构造更复杂的正则表达式.

But if there is no threshold = X string, it will fail. You should construct more complex regular expression for that case.

这篇关于正则表达式 ansible lineinfile 小节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆