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

查看:107
本文介绍了正则表达式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,并且要确保将其设置为特定值,则可以使用此regexp:

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'

它在<disk>...<alarm>...<#boot>...<error>...中搜索第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天全站免登陆