'How to add multiple lines in all files present in a directory using Ansible
In Ansible script, First I'm using find_module to find all files in a directory, and then I'm using set_fact to mention all commands that I want to add in all files and then I am using lineinfile module to add multiple lines in all the files, but it is adding all commands in list format ['line1','line2','line3'] instead of this I want these lines to be added one after another in all files. Below mentioned is the script
tasks:
- name: finding all files present in something directory
find:
paths: /etc/something.d/
file_type: file
patterns: '*.d'
register: c1
become: true
- set_fact:
lines:
- "line1"
- "line2"
- "line3"
- lineinfile:
path: "{{ item.path }}"
line: "{{ lines}}"
state: present
create: yes
backup: yes
register: c2
become: true
with_items: "{{ c1.files }}"
- debug:
var: c1
- debug:
var: c2
Solution 1:[1]
So... the old way, which I prefer, is with_nested
:
set_fact:
lines:
- line1
- line2
- line3
lineinfile:
...
...
with_nested:
- "{{ c1.files }}"
- "{{ lines }}"
The new way, and I have no idea what escapee from a Ph.D. CS program came up with this, is to combine the lists:
set_fact:
lines:
- line1
- line2
- line3
lineinfile:
...
...
loop: "{{ c1.files | product | lines | list }}"
https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#with-nested-with-cartesian
If all the lines are together, you might want to look at blockinfile
.
Solution 2:[2]
I was able to add multiple lines in all files present in a directory by using below mentioned ansible script, However the problem now is all lines are getting duplicated, if I run this script again, Please suggest any way so that lines won't get duplicated in all files
tasks:
- name: finding all files present in something directory
find:
paths: /etc/something.d/
file_type: file
patterns: '*.d'
register: c1
become: true
- set_fact:
lines:
- "line1"
- "line2"
- "line3"
- lineinfile:
path: "{{ item.path }}"
line: "{{ lines[0]+'\n'+lines[1]+'\n'+lines[2]+'\n'}}"
state: present
create: yes
backup: yes
register: c2
become: true
with_items: "{{ c1.files }}"
- debug:
var: c1
- debug:
var: c2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jack |
Solution 2 |