regex Ansible -用ansible.builtin.replace模块替换文件中两个指定行之间的所有文本

wkftcu5l  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(106)

我一直在尝试使用Ansible替换配置文件中两个指定行之间的所有文本。
在这个任务块中,我只是想删除指定的两行之间的所有文本。在下一个任务中,我将在这两行之间添加新的配置。
感谢任何指导/帮助,谢谢!

- name: Remove all lines between specified lines in hosts file.
        ansible.builtin.replace:
          path: /etc/hosts
          after: "^#BeginEntries$"
          before: "^#EndEntries$"
          regexp: '.*'
          replace: ""
          backup: yes

字符串
当前任务块似乎与我的after/before不匹配。即使指定文件中确实存在这两行,也不会更改任何内容。

czq61nw1

czq61nw11#

如果你的最终目标是替换这些行之间的内容,你应该使用ansible.builtin.blockinfile模块和state: present,并立即替换它!请参阅:

文本.txt

123
#BeginEntries
bad_entry_1
bad_entry_2
#EndEntries
321

字符串

playbook.yaml

- name: Replace block
  hosts: localhost
  tasks:
    - name: Replace block
      ansible.builtin.blockinfile:
        path: "{{ playbook_dir }}/text.txt"
        marker: "#{mark}"
        marker_begin: "BeginEntries"
        marker_end: "EndEntries"
        state: present
        content: |
          my awsome content with

          even

          multiple

          blank

          lines


输出量:

❯ ansible-playbook playbook.yaml -i localhost,

PLAY [Replace block] *************************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************
ok: [localhost]

TASK [Replace block] *************************************************************************************************************************
changed: [localhost]

PLAY RECAP ***********************************************************************************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

❯ cat text.txt
123
#BeginEntries
my awsome content with

even

multiple

blank

lines
#EndEntries
321


在上面的例子中,我们定义了marker本身(starting #),然后BeginList和EndList作为begin和end块。没有必要使用正则表达式,因为在这种情况下- match将是精确的。
如果你真的希望这是一个两步操作(删除然后修改),你也可以使用这个模块,但要注意的是,你最终会得到标记之间的空字符串(根据文档,空的“content”或“block”会导致state: absent

- name: Remove block
  hosts: localhost
  tasks:
    - name: Remove block
      ansible.builtin.blockinfile:
        path: "{{ playbook_dir }}/text.txt"
        marker: "#{mark}"
        marker_begin: "BeginEntries"
        marker_end: "EndEntries"
        state: present
        content: "{{ '\n' }}"


那么text.txt的输出将是

❯ cat text.txt
123
321
#BeginEntries

#EndEntries


关于replace模块的例子,似乎“^”和“$”标记在replace模块的before和after参数中的多行模式下不起作用,这可能是你没有得到预期结果的原因。你可以通过使用换行符来解决这个问题,如下所示:

ansible.builtin.replace:
        path: "{{ playbook_dir }}/text.txt"
        after: "\n#BeginEntries\n"
        before: "\n#EndEntries\n"
        regexp: '.*'
        replace: ""


将导致

123
#BeginEntries

#EndEntries
321


但我仍然强烈建议使用blockinfile模块,因为它基本上是为您的用例而设计的。

相关问题