Using ansible to append a string to the end of a line

image_pdfimage_print

I am using ansible to apply security hardening to CentOS6 VMs. We are following the 179 page CIS security benchmark:
http://benchmarks.cisecurity.org/downloads/show-single/?file=centos6.100

Thanks for the heads up to Philippe Eveque for the complicated regex and backrefs example:
https://groups.google.com/d/msg/ansible-project/JvHfchsgRaU/Vw_CzBbvadgJ

This code will add audit=1 to the end of any line starting with “kernel”

 - name: 4.2.3 Enable Auditing for Processes That Start Prior to auditd
   lineinfile: dest=/etc/grub.conf
               backup=True
               backrefs=True
               state=present
               regexp='(^\s+kernel(\s+(?!audit=1)[\w=/\-\.]+)*)\s*$'
               line='\1 audit=1'

6 thoughts on “Using ansible to append a string to the end of a line

  1. Just a little remark… This code doesn’t work with all kernel options.

    You should add _ and , to the list. Console uses , and _ for a lot of other option (althought that might be covered by \w.

    Thank you for putting this piece online.

  2. The small fix in question. And no, the \w does not cover it if , and _ are not listed.
    – name: 4.2.3 Enable Auditing for Processes That Start Prior to auditd
    lineinfile: dest=/etc/grub.conf
    backup=True
    backrefs=True
    state=present
    regexp='(^\s+kernel(\s+(?!audit=1)[\w=/\-\.\,\_]+)*)\s*$’
    line=’\1 audit=1′

  3. Thanks for the comments regarding improved regex for grub.conf. The main point of the post was a reminder to myself of how to use backrefs in ansible’s lineinfile module.

    Cheers,
    Jon

  4. Hi there,

    I tried this out and it only appended the last line with the instance of kernel. The only syntax change made was the destination file path. I don’t think I know enough about the regexp syntax to follow everything going on. Not sure why it’s only appending the line it finds kernel.

    Appreciate any of the support. And thanks for posting this documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments Protected by WP-SpamShield Spam Blocker