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.
1 |
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
1 2 3 4 5 6 |
- name: uncomment a line lineinfile: dest=/etc/lighttpd/lighttpd.conf regexp='^ include "mod_fastc gi.conf"' insertafter='^# include "mod_fastc gi.conf"' line=' include "mod_fastc gi.conf"' state=present |
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. insertafter
and insertbefore
with BOF/EOF do not work as expected
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
--- - hosts: alpine_install user: root tasks: # - name: create a complete empty file # command: /usr/bin/touch /test/test.conf - name: create a new file with lineinfile lineinfile: dest=/test/test.conf regexp='^' line='' state=present create=True - name: add a string to the new file lineinfile: dest=/test/test.conf regexp='^' line='Hello, World!' state=present - 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 lineinfile: dest=/test/test.conf regexp='^' line='#This is a comment\n#Another comment\n#Another comment, again\n#Again a comment\n#The last comment' state=present - name: add a single line, in this case the same as the comment but uncommented lineinfile: dest=/test/test.conf regexp='^Another' insertafter='^#Another' line='Another comment, no longer a comment' state=present - name: remove the line '#Again a comment' lineinfile: dest=/test/test.conf regexp='^#Again' state=absent - name: add a new string at the beginning of the file lineinfile: dest=/test/test.conf regexp='^This' insertbefore=BOF line='This is no longer a comment' - name: add a new string before the match lineinfile: dest=/test/test.conf regexp='^Another' insertbefore='^#Another' line='Another comment, no longer' - name: add a new string at the end of the file lineinfile: dest=/test/test.conf regexp='' insertafter=EOF line='The latest entry' |
The test.conf file will look like this at the end.
1 2 3 4 5 6 7 8 |
$ cat test.conf This is no longer a comment #This is a comment #Another comment #Another comment, again Another comment, no longer #The last comment The latest entry |
Excellent…
Thanks, helped me a lot!