首页 > 解决方案 > 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

标签: 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

然后在你的任务中 -

- replace:
    path: /your/file
    regexp: '^{{ item.key }}=.*$'
    replace: '{{ item.key }}={{ item.value }}'
  with_dict: "{{ test_entries }}"

我还经常使用一组匿名字典,以及我命名属性的任何名称,而不是keyand value。主要区别在于它允许您控制顺序(在这里似乎无关紧要)并跳过key&value关键字。


推荐阅读