How do you Ensure a Line Exists and is Uncommented

2019-06-20 07:58发布

问题:

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"

回答1:

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.