使用Ansible修改范围中的一行 [英] Modify a line in a scope with Ansible

查看:143
本文介绍了使用Ansible修改范围中的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要修改文件中的一行.唯一的问题,该行出现了多次,但范围不同.就像在wso2配置手册中的本示例中一样:

I need to modify a line in a file. Only problem, the line appears multiple times, but in different scopes. Like in this example from wso2 configuration manual :

<KeyStore>
    <Location>${carbon.home}/resources/security/wso2carbon.jks</Location>
    <Type>JKS</Type>
    <Password>wso2carbon</Password>
    <KeyAlias>wso2carbon</KeyAlias>
    <KeyPassword>wso2carbon</KeyPassword>
</KeyStore>

<TrustStore>
    <!-- trust-store file location -->
    <Location>${carbon.home}/repository/resources/security/client-truststore.jks</Location>
    <!-- trust-store type (JKS/PKCS12 etc.) -->
    <Type>JKS</Type> 
    <!-- trust-store password -->
    <Password>wso2carbon</Password>
</TrustStore>

例如,我需要使用<Keystore>范围的一个值和<TrustStore>范围的第二个不同的值来修改<Password>条目,以具有不同的密码. lineinfile模块可以这样做吗?还是有其他方法吗?

I would need for example to modify the <Password> entry with one value in the <Keystore> scope, and with a second different value in the <TrustStore> scope in order to have different passwords. Can the lineinfile module do that ? Or is there any other way ?

PS. 使用模板不是我想要的解决方案,因为我想使用它来修改现有服务器,而不会丢失任何本地修改.

PS. Using a template is not the solution I am looking for, as I would like to use this to modify preexisting servers and not lose any local modification.

推荐答案

您不能使用 lineinfile ,因为它分别处理文件的每一行–因此没有其他行的上下文.
lineinfile中的正则表达式不是多行.

You can't do this with lineinfile, because it handles every line of the file separately – so there's no context from other lines possible.
Regex in lineinfile is not multiline.

您可以使用替换 –它使用多行正则表达式.
例如:

You can use replace – it uses multiline regex.
For example:

- replace:
    backup: yes
    dest: config.xml
    regexp: '(<{{ item.scope }}>[\S\s]*<Password>)(?!{{ item.password }}<).*(</Password>[\S\s]*</{{ item.scope }}>)'
    replace: '\1{{ item.password }}\2'
  with_items:
    - scope: KeyStore
      password: foo
    - scope: TrustStore
      password: bar

请记住,此解决方案不是防弹的-作用域名称和密码不应包含任何XML特殊字符或正则表达式序列.我也不能肯定地说它如何处理具有相同作用域名称的嵌套XML块.
但对于一般情况,应该没问题.
甚至有尝试成为幂等的–如果密码相同,它将不会与阻止匹配.

Keep in mind that this solution is not bulletproof – scope names and password shouldn't have any XML special characters or regular expression sequences. Also I can't say for sure how it handles nested XML blocks with the same scope name.
But for general cases it should be fine.
There's even a try to be idempotent – it will not match a block if the password is the same.

这篇关于使用Ansible修改范围中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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