Ansible Regex – Fixing Incorrect Regex to Add a Block in a File

ansibleregex

I'd like to add a block between <IfModule mod_ssl.c> and </IfModule> in /etc/apache2/mods-available/ssl.conf with the ansible task shown below. I use blockinfile and insertbefore.

Unfortunately the block is always added after </IfModule> at the bottom of the file. I guess my regex is wrong.

- name: Apache2 > update SSL conf
  become: yes
  blockinfile:
    path: /etc/apache2/mods-available/ssl.conf
    block: |
      # Requires Apache >= 2.4
      SSLCompression off
      SSLUseStapling on
      SSLStaplingCache "shmcb:logs/stapling-cache(150000)"

      # Requires Apache >= 2.4.11
      SSLSessionTickets Off

      Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains"
      Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
    marker: ""
    insertbefore: '^<\/IfModule>'
  notify:
    - Restart apache2

I have tried the following regex without success:

insertbefore: '/^<\/IfModule>/m'
insertbefore: "<\/IfModule>"
insertbefore: "</IfModule>"
insertbefore: "</IfModule> "
insertbefore: '^<\/IfModule>$'
insertbefore: "&lt;/IfModule&gt;"
insertbefore: '(?m)^<\/IfModule>\\s?$'
insertbefore: '^</IfModule>\s?$'

I would be very grateful if anyone could help me to fix my regex.
Thanks.

Best Answer

Short Story:
the winner regex is insertbefore: "^</IfModule>\\s?$"

Long Story:
I got another idea to get everything done:
- first, one task to remove </IfModule> at the bottom of the file
- second, one task to add the block at the bottom of the file
- third, one task to add </IfModule> at the bottom of the file

I wrote the first new task:

- name: Apache2 > Removes </IfModule>
  become: yes
  lineinfile:
    dest: /etc/apache2/mods-available/ssl.conf
    regexp: "^</IfModule>\\s?$"
    state: absent

and I realized I'd just written the right regex... My mistake was to escape /.
:-)

Correct task that manages everything by itself:

- name: Apache2 > update SSL conf
  become: yes
  blockinfile:
    path: /etc/apache2/mods-available/ssl.conf
    block: |
      # Requires Apache >= 2.4
      SSLCompression off
      SSLUseStapling on
      SSLStaplingCache "shmcb:logs/stapling-cache(150000)"

      # Requires Apache >= 2.4.11
      SSLSessionTickets Off

      ## HSTS (mod_headers is required) (15768000 seconds = 6 months)
      Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains"

      ## Transmit cookies over secure connection only
      Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
    insertbefore: "^</IfModule>\\s?$"
  notify:
    - Restart apache2

Anx's comment made me put back blockinfile markers to keep the task idempotent.