Ubuntu 如何通过ansible playbook在图案后添加线条
我有文件名测试Ubuntu 如何通过ansible playbook在图案后添加线条,ubuntu,ansible,centos,Ubuntu,Ansible,Centos,我有文件名测试 [tag1] [tag2] 我想在我找到这个解决方案的测试中,在[tag1]之后添加行 - name: Add content lineinfile: path: test insertafter: '[tag1]' line: "{{ item }}" with_items: - '# This is line 1' - '# This is line 2' - '# This is
[tag1]
[tag2]
我想在我找到这个解决方案的测试中,在[tag1]之后添加行
- name: Add content
lineinfile:
path: test
insertafter: '[tag1]'
line: "{{ item }}"
with_items:
- '# This is line 1'
- '# This is line 2'
- '# This is line 3'
但它会将这些行添加到文件末尾,而不是[tag1]之后
如果我运行playbook两次,它会添加两次,我想检查这些行在[tag1]添加它们之后是否不存在,如果存在,则什么也不做
我该怎么办?
为什么在文件末尾添加行?不一致。看
这是由firstmatch周围的逻辑中的错误引起的。这个bug一直存在于devel中,直到Ansible 2.5
在下面的任务中
- lineinfile:
path: test
insertafter: '[tag1]'
firstmatch: yes
line: "{{ item }}"
loop:
- '# This is line 1'
- ini_file:
path: test
section: "{{ item.section }}"
option: "{{ item.option }}"
allow_no_value: yes
loop:
- section: 'tag1'
option: '# This is line 1'
- section: 'tag1'
option: '# This is line 2'
参数firstmatch:yes
有助于将行
置于[tag2]
$ cat test
[tag1]
# This is line 1
[tag2]
,但当重复播放时,相同的参数会导致重复添加行
。(请随意尝试。)
改用。下面的任务
- lineinfile:
path: test
insertafter: '[tag1]'
firstmatch: yes
line: "{{ item }}"
loop:
- '# This is line 1'
- ini_file:
path: test
section: "{{ item.section }}"
option: "{{ item.option }}"
allow_no_value: yes
loop:
- section: 'tag1'
option: '# This is line 1'
- section: 'tag1'
option: '# This is line 2'
给出幂等结果
$ cat test
[tag1]
# This is line 2
# This is line 1
[tag2]
如果我多次运行playbook,如何防止重复添加行。我想检查行是否存在,不要添加它们。最好使用template、blockinfile和ini_文件。在非常简单的情况下使用
lineinfle
作为最后一个选项。特别是当文件中有标记时,请使用ini_文件。我不知道如何检查行是否存在。我如何通过ini_文件控制它。请给我一个示例?当然。为什么在运行播放之前要知道文件中是否存在行?重要吗?否。重要的是,在播放完成后,文件中将出现哪些行。这是一种哲学,用来定义一个系统的状态。要插入多行,只需将项目添加到循环中。请看。我想运行playbook多次,我想确保不会多次添加一行