It appears when I repeatedly use blockinfile in an Ansible script on the same file, it overwrites any text that was previously in the file before. I’m running version 2.2 and I’m noticing it’s also defining markers in the file that aren’t referenced in my Ansible script. I’ve also tried specifying insertafter: EOF and insertafter: “previous line syntax”, but it seems I can only use the blockinfile module once in the script, from the overwrites. Any advice on how to resolve?
Can you give me more details like your script and file you are changing.
Sure, please see below:
---
- hosts: all
remote_user: local_user
become: yes
become_user: root
become_method: sudo
vars_prompt:
- name: "set_newsite"
prompt: "What is the name of the new site to create?"
private: no
tasks:
- name: Create new config file
file:
state: touch
path: "/var/www/html/{{ set_newsite }}.cfg"
owner: apache2
group: apache2
mode: 0644
- name: Add test data to config file
blockinfile:
dest: "/var/www/html/{{ set_newsite }}.cfg"
block: |
test1
test2
test3
- name: Confirm variable insertion into test config file
lineinfile:
destfile: "/var/www/html/{{ set_newsite }}.cfg"
insertafter: "test3"
line: 'Name of new site is: {{ set_newsite }}'
- name: Second confirmation
when: set_newsite | match("198.7.203.")
lineinfile:
destfile: "/var/www/html/{{ set_newsite }}.cfg"
insertafter: "Name of new site"
line: 'new variable'
- name: Add more block data to test config file
blockinfile:
dest: "/var/www/html/{{ set_newsite }}.cfg"
insertafter: EOF
block: |
test4
test5
test6
It’s a simple script that adds lines in a test config file to ensure the basics work before I add code to it. When I edit out the second ‘blockinfile’ command, I get everything before the word ‘test4’, so I’m definitely seeing something is up.
When using several blockinfile on same file it's essential that you set unique marker for each blockinfile, if not the second one will overwrite the first one.
I see. Thanks Kai, I’ll give it a try.