Reputation: 33
I have file name test
[tag1]
[tag2]
I want to add lines after [tag1] in test I find this solution
- name: Add content
lineinfile:
path: test
insertafter: '[tag1]'
line: "{{ item }}"
with_items:
- '# This is line 1'
- '# This is line 2'
- '# This is line 3'
But it add those line at the end of file not after [tag1] And If I run playbook twice it added it 2 times I want to check if those lines are not exist after [tag1] add them and if exist do nothing.
What should I do? Why it added lines at the end of file?
Upvotes: 1
Views: 1380
Reputation: 68134
lineinfile is not consistent. See lineinfile is not idempotent #58923.
This is caused by a bug in the logic around firstmatch. This bug is present in devel all the way back to Ansible 2.5 ...
In the task below
- lineinfile:
path: test
insertafter: '[tag1]'
firstmatch: yes
line: "{{ item }}"
loop:
- '# This is line 1'
the parameter firstmatch: yes
helps to put the line
before [tag2]
$ cat test
[tag1]
# This is line 1
[tag2]
, but when the play is repeated the same parameter causes the line
to be added repeatedly. (Feel free to try.)
Use ini_file instead. The task below
- 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'
gives the idempotent result.
$ cat test
[tag1]
# This is line 2
# This is line 1
[tag2]
Upvotes: 2