Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you Ensure a Line Exists and is Uncommented with Ansible LineinFile?

How do you ensure a specific line exists in a file and is uncommented with ansible's `lineinfile'

The line I want uncommented (in .htaccess):

#php_flag display_errors on

I have used the following:

  - name: Make sure PHP Errors are turned on
    lineinfile: dest={{ www_path }}/.htaccess line="php_flag display_errors on"
like image 793
tread Avatar asked Oct 17 '15 07:10

tread


1 Answers

Actually your example works as is:

Contents of the .htaccess file:

#php_flag display_errors on

The ansible play:

- name: Make sure PHP Errors are turned on
  lineinfile: 
    dest: "{{ www_path }}/.htaccess"
    line: "php_flag display_errors on"

Results of ansible-playbook with this play:

$ cat .htaccess
#php_flag display_errors on
php_flag display_errors on

If the file starts with the line commented you'll see a second line uncommented. To correct this, use a regexp that will match the existing line and replace it:

- lineinfile:
    dest: /Users/bwhaley/tmp/file
    regexp: '^#php_flag display_errors'
    line: 'php_flag display_errors'
    backrefs: yes

Note though that with backrefs: yes if the line you want uncommented is not already present and commented, the play will make no change at all.

like image 174
Ben Whaley Avatar answered Sep 30 '22 00:09

Ben Whaley