ansibleansible-2.x

In Ansible, how to add a block of text at end of a file with a blank line before the marker?


I have a playbook as shown below:

- hosts: localhost
  tasks:
    - name: update a file
      blockinfile:
        dest: /tmp/test
        block: |
          line 1
          line 2

Upon running the playbook, the file /tmp/test becomes:

a # this is the end line of the original file
# BEGIN ANSIBLE MANAGED BLOCK
line 1
line 2
# END ANSIBLE MANAGED BLOCK

I would like to add a blank line (newline) before the marker "# BEGIN ANSIBLE MANAGED BLOCK" for visual effect.
What is the easiest way to do it? Preferably within the task, but any idea is welcome. If I redefine the marker, it will affect both the "BEGIN" and "END" marker.


Solution

  • If you have a file that looks like this:

    some line
    foobar
    some other line
    

    and you want to add a newline before the pattern "foobar" in this example, the following ansible code will do it for you:

    - hosts: localhost
      gather_facts: no
      connection: local
      tasks:
        - name: update a file
          replace:
            dest: /tmp/foobar
            regexp: |
              (?mx)     # "m" lets ^ and $ match next to imbedded \n, x allows white space for readability
              (?<!\n\n) # a Zero-Length Assertion that it does not have an empty line already
              ^         # beginning of the line
              (foobar)  # match "foobar" and save it as \1, it could be "\#\ BEGIN\ ANSIBLE\ MANAGED\ BLOCK" if that is your pattern
              $         # end of line
            replace: "\n\\1" # add a newline before the matched pattern
    

    and it is idempotent and it does not add the newline at the end of the file when the pattern is not present.