Search code examples
ansibleansible-2.xansible-inventory

Space issue while filtering with Ansible


<IfModule security2_module>
        # Default Debian dir for modsecurity's persistent data
        SecDataDir /var/cache/modsecurity

        # Include all the *.conf files in /etc/modsecurity.
        # Keeping your local configuration in that directory
        # will allow for an easy upgrade of THIS file and
        # make your life easier
        IncludeOptional /etc/modsecurity/*.conf

        # Include OWASP ModSecurity CRS rules if installed
        IncludeOptional /usr/share/modsecurity-crs/*.load
</IfModule>

What i am trying to do is

1) Remove the line " IncludeOptional /usr/share/modsecurity-crs/*.load " from the file.

2) Add line " Include /etc/modsecurity/rules/.conf " after line " IncludeOptional /etc/modsecurity/.conf " in the file

Ansible script i used was

- name: Removing line from file
  lineinfile:
     dest: /etc/apache2/mods-enabled/security2.conf
     regexp: 'IncludeOptional /usr/share/modsecurity-crs/*.load'
     state: absent
- name: Insert new line in the file after line
  lineinfile:
    dest: /etc/apache2/mods-enabled/security2.conf
    line: 'Include /etc/modsecurity/rules/*.conf'
    insertafter: 'IncludeOptional /etc/modsecurity/*.conf'   

But due to the spaces in front of the line, i am unable to add or remove any line. Am i doing any wrong in specifying regular expression.

What i am trying to achieve finally is :

<IfModule security2_module>
        # Default Debian dir for modsecurity's persistent data
        SecDataDir /var/cache/modsecurity

        # Include all the *.conf files in /etc/modsecurity.
        # Keeping your local configuration in that directory
        # will allow for an easy upgrade of THIS file and
        # make your life easier
        IncludeOptional /etc/modsecurity/*.conf
        Include /etc/modsecurity/rules/*.conf

        # Include OWASP ModSecurity CRS rules if installed
</IfModule>

Solution

  • Your tasks require a bit of update and mainly in the regex, please use the following ansible tasks to achieve the desired results.

    - name: Removing line from file
      lineinfile:
         dest: test.sh
         regexp: '^\s*IncludeOptional /usr/share/modsecurity-crs/\*.load'
         state: absent
    
    - name: Insert new line in the file after line
      lineinfile:
        dest: test.sh
        line: '        Include /etc/modsecurity/rules/*.conf'
        insertafter: '^\s*IncludeOptional /etc/modsecurity/\*.conf'
    

    The first task removes the line from the file and the second task inserts the given line after the pattern is found.