使用 Ansible 修改范围内的一行 [英] Modify a line in a scope with 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>
例如,我需要在
范围内使用一个值修改
条目,并在
范围内使用另一个不同的值code><TrustStore> 范围以便具有不同的密码.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. 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.
您可以使用 replace - 它使用多行正则表达式.
例如:
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屋!