gpt4 book ai didi

ansible - 在 Ansible 中,如何将一行移动到一个 block 中?

转载 作者:行者123 更新时间:2023-12-05 07:01:19 27 4
gpt4 key购买 nike

我有一种情况,我想将文本文件中的现有行包含到一个新 block 中。

line 1
line 2
line in block
line 3
line 4

应该变成

line 1
line 2
line 3
line 4
# BEGIN MyBlock
line in block
other line in block
# END MyBlock

创建 block 当然涉及到 blockinfile 模块:

- blockinfile:
path: /etc/myfile
marker: "# {mark} MyBlock"
block: |
line in block
other line in block

lineinfile 可用于删除一行:

- lineinfile:
path: /etc/myfile
line: 'line in block'
state: absent

但是这个解决方案可能会删除 block 内的行,而不是原来的行。

最佳答案

连续执行 lineinfileblockinfile。第一个将删除它,第二个将包含它。最后,它会在正确的地方。比它可能的更脏,但它有效。

更新:在那种情况下,一个可行的幂等解决方案是:

  - name: Slurp file
slurp:
src: myfile
register: myfile

- name: Remove line if not in block
lineinfile:
path: myfile
line: 'line in block'
state: absent
when: >
not (myfile.content
| b64decode
| regex_search('# BEGIN MyBlock(\n.*)*\nline in block(\n.*)*\n# END MyBlock'))

- name: Add block
blockinfile:
path: myfile
marker: "# {mark} MyBlock"
block: |
line in block
other line in block

关于ansible - 在 Ansible 中,如何将一行移动到一个 block 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63895416/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com