我有以下 Ansible 变量:
test_entries:
"
test-auth-ip=192.168.1.22
test-auth-serv=example1.com
test-auth-net=192.168.1.254
test-auth-blabla=test123
"
我还有一个文本文件,其中包含以下几行:
test-auth-str1=null
test-auth-str2=null
test-auth-serv=null
test-auth-net=0.0.0.0
test-auth-str3=null
test-auth-str4=null
我希望能够替换文件中与变量中的行匹配的任何行,直到“=”符号。 (正则表达式:^test-auth(.*?=))
我阅读了 Ansible 文档。用于“lineinfile”和“替换”功能。然而, 我找不到如何使用正则表达式逐行匹配。
预期结果
test-auth-str1=null
test-auth-str2=null
test-auth-serv=example1.com
test-auth-net=192.168.1.254
test-auth-str3=null
test-auth-str4=null
最佳答案
尝试
test_entries:
test-auth-ip : 192.168.1.22
test-auth-serv : example1.com
test-auth-net : 192.168.1.254
test-auth-blabla : test123
然后在你的任务中 -
- replace:
path: /your/file
regexp: '^{{ item.key }}=.*$'
replace: '{{ item.key }}={{ item.value }}'
with_dict: "{{ test_entries }}"
我还经常使用匿名字典数组,以及我命名的属性,而不是key
和value
。主要区别在于它允许您控制顺序(这在这里似乎并不重要)并跳过 key
和 value
关键字。
关于Ansible 替换变量中的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50366522/