[colug-432] Automatically Edit Configuration File: Ansible Replace Module Using Its Multiline Ability

jep200404 at columbus.rr.com jep200404 at columbus.rr.com
Thu Nov 19 11:03:45 EST 2015

On Thu, 19 Nov 2015 04:10:32 +0000, Greg Sidelinger <gate at ilive4code.net> wrote:

> On Wed, Nov 18, 2015 at 10:26 PM <jep200404 at columbus.rr.com> wrote:
> > How would you automate the editing of a configuration file as
> > described below?
> >
> > I am automating the configuration of a system with Ansible.
> > For /etc/httpd/conf/httpd.conf, I need to make sure that the
> > <Directory /> section has a "Require all granted" line instead
> > of a "Require all denied" line. "Require all" lines in other
> > sections need to be left alone.

> Try the replace module.
> http://docs.ansible.com/ansible/replace_module.html

At the top of that page, it says:

    replace - Replace all instances of a particular string in a 
    file using a back-referenced regular expression.

Uh oh, I don't want to replace all instances,
just the one in the <Directory /> section.

However, I see that its regexp handles multiple lines,
so a complicated regex was able to do the replacement 
only in the <Directory /> section.

    - name: Require all granted for Directory / section.
      replace: dest=/etc/httpd/conf/httpd.conf regexp='(\n<Directory />.*\n(.*\n)*? *Require *all *)denied(\W(.*\n)*?</Directory>)' replace='\1granted\3' backup=yes

It is a gnarly regex, but it works. The multiline handling was 
the key difference between the lineinfile and replace modules.

Thanks Greg.

Now to check out Jim Wildman's suggestion,
which could greatly simplify things.

More information about the colug-432 mailing list