Ansible 替换变量中的多行

标签 ansible

我有以下 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 }}"

我还经常使用匿名字典数组,以及我命名的属性,而不是keyvalue。主要区别在于它允许您控制顺序(这在这里似乎并不重要)并跳过 keyvalue 关键字。

关于Ansible 替换变量中的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50366522/

相关文章:

Ansible:覆盖额外变量中的字典变量

javascript - 让 Ansible 与 Pulumi 一起工作可能吗?

python - 无法多次运行ansible的k8s模块(非幂等)

ansible - 为什么带有 state=absent 的 blockinfile 不适用于这些行?

ansible - 未从 list 文件中选取主机

mysql - 使用 Ansible mysql_db 模块生成的 sql 转储文件中的数据库特异性

ansible - 将变量传递给包含的剧本

ssh - Ansible ad-hoc 命令有效,但运行 playbook 无法使用 ssh 进行身份验证

linux - Ansible 剧本

ansible - 使用 Ansible 管理客户主机和应用程序的最佳实践