我有一个如下所示的剧本:
- hosts: localhost
tasks:
- name: update a file
blockinfile:
dest: /tmp/test
block: |
line 1
line 2
运行 playbook 后,文件 /tmp/test
变为:
a # this is the end line of the original file
# BEGIN ANSIBLE MANAGED BLOCK
line 1
line 2
# END ANSIBLE MANAGED BLOCK
为了视觉效果,我想在标记“# BEGIN ANSIBLE MANAGED BLOCK
”之前添加一个空行(换行符),最简单的方法是什么?最好在任务内,但欢迎任何想法。如果我重新定义标记,它将同时影响“BEGIN”和“END”标记。
最佳答案
使用lineinfile。例如
- hosts: localhost
tasks:
- name: update a file
blockinfile:
dest: /tmp/test
block: |
line 1
line 2
- name: insert empty line before the marker
lineinfile:
dest: /tmp/test
insertbefore: '^# BEGIN ANSIBLE MANAGED BLOCK$'
line: ''
不幸的是,insertbefore 不适用于更多 block 。如果您坚持在 block 之间留空行,则可能需要 template 模块。
试试下面的剧本。不幸的是,EOF 没有按预期工作
shell> cat manage-block.yml
- name: "insert {{ my_marker }} in {{ my_dest }}"
blockinfile:
dest: "{{ my_dest }}"
marker: "# {mark} ANSIBLE MANAGED BLOCK {{ my_marker }}"
block: "{{ my_block }}"
- name: "insert empty line before {{ my_marker }}"
lineinfile:
dest: "{{ my_dest }}"
insertbefore: '^# BEGIN ANSIBLE MANAGED BLOCK {{ my_marker }}'
line: 'empty line'
when: ansible_loop.first
- name: "insert empty line after EOF"
lineinfile:
dest: "{{ my_dest }}"
insertafter: EOF
line: 'empty line'
- hosts: localhost
vars:
my_blocks:
/tmp/test:
- my_marker: block001
my_block: |
line 1
line 2
- my_marker: block002
my_block: |
line 3
line 4
tasks:
- include_tasks: manage-block.yml
with_subelements:
- "{{ my_blocks|dict2items }}"
- value
loop_control:
extended: true
vars:
my_dest: "{{ item.0.key }}"
my_marker: "{{ item.1.my_marker }}"
my_block: "{{ item.1.my_block }}"
关于ansible - 在ansible中如何在文件末尾添加一个文本 block ,标记前有一个空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64687350/