By default Ansible blockinfile inserts the block without a leading empty line:
127.0.0.1 localhost
xxx.xxx.xxx.xxx derico.de
### BEGIN ANSIBLE MANAGED BLOCK ###
xxx.xxx.xxx.xxx mail.lan
### END ANSIBLE MANAGED BLOCK ###
Like other people on Reddit, i don't like it this. To make it more readable, we would like to add an empty line before that block:
- name: update /etc/hosts file with a list of lan-hosts
become: true
blockinfile:
path: /etc/hosts
block: "{{ lookup('template', 'templates/etc/lan-hosts.j2') }}"
state: present
marker: "### {mark} ANSIBLE MANAGED BLOCK ###"
backup: yes
- name: insert an empty line before the marker line
become: true
replace:
path: /etc/hosts
regexp: "(?<=.\n)### BEGIN ANSIBLE MANAGED BLOCK ###$"
replace: "\n### BEGIN ANSIBLE MANAGED BLOCK ###"
The regex matches the marker line, when there is no empty line right before it and replaces it with a marker which has a leading empty line:
127.0.0.1 localhost
xxx.xxx.xxx.xxx derico.de
### BEGIN ANSIBLE MANAGED BLOCK ###
xxx.xxx.xxx.xxx mail.lan
### END ANSIBLE MANAGED BLOCK ###