While working with Ansible and files, like configuration files or default files for services, often it’s useful to just change one line than copy a template file. The
lineinfile module provides functionality like
sed. Usually I did like the example below with
sed because I was more familiar with
sed than with re of Python.
command: sed -i 's|# include "mod_fastc gi.conf"|include "mod_fastc gi.conf"|g' /etc/lighttpd/lighttpd.conf
Converted for a playbook task entry
- name: uncomment a line
regexp='^ include "mod_fastc gi.conf"'
insertafter='^# include "mod_fastc gi.conf"'
line=' include "mod_fastc gi.conf"'
The below is a simple collection of the different use cases of the
lineinfile module. It took me some time to figure out how the module works.
insertbefore with BOF/EOF do not work as expected
- hosts: alpine_install
# - name: create a complete empty file
# command: /usr/bin/touch /test/test.conf
- name: create a new file with lineinfile
- name: add a string to the new file
- name: add a multiline string to the file and delete the string from before
# Be aware, with the given regex the string will be added everytime the playbook runs
line='#This is a comment\n#Another comment\n#Another comment, again\n#Again a comment\n#The last comment'
- name: add a single line, in this case the same as the comment but uncommented
line='Another comment, no longer a comment'
- name: remove the line '#Again a comment'
- name: add a new string at the beginning of the file
line='This is no longer a comment'
- name: add a new string before the match
line='Another comment, no longer'
- name: add a new string at the end of the file
line='The latest entry'
The test.conf file will look like this at the end.
$ cat test.conf
This is no longer a comment
#This is a comment
#Another comment, again
Another comment, no longer
#The last comment
The latest entry