ansible: lineinfile for several lines?
The same way there is a module lineinfile
to add one line in a file, is there a way to add several lines?
I do not want to use a template because you have to provide the whole file. I just want to add something to an existing file without necessarily knowing what the file already contains so a template is not an option.
Solution 1:
You can use the lineinfile
built-in in a loop. Here's an example:
- name: Set some kernel parameters
lineinfile:
dest: /etc/sysctl.conf
regexp: "{{ item.regexp }}"
line: "{{ item.line }}"
loop:
- { regexp: '^kernel.shmall', line: 'kernel.shmall = 2097152' }
- { regexp: '^kernel.shmmax', line: 'kernel.shmmax = 134217728' }
- { regexp: '^fs.file-max', line: 'fs.file-max = 65536' }
Solution 2:
You can try using blockinfile
instead.
You can do something like
- blockinfile: |
dest=/etc/network/interfaces backup=yes
content="iface eth0 inet static
address 192.168.0.1
netmask 255.255.255.0"
Solution 3:
Here is a noise-free version of the solution which is to use with_items:
- name: add lines
lineinfile:
dest: fruits.txt
line: '{{ item }}'
with_items:
- 'Orange'
- 'Apple'
- 'Banana'
For each item, if the item exists in fruits.txt no action is taken.
If the item does not exist it will be appended to the end of the file.
Easy-peasy.