Well did you received a request or requirement for adding simple one line to a file on multiple or thousands of server. Then thinking of login on to each server and appending a line may take a while. There is super-way to add line in file on multiple servers using Ansible.
Add line in file on multiple servers using Ansible in minutes
In order to accomplish above task to “add line in file on multiple servers using Ansible” , we will using the module present in Ansible called as “lineinfile“. Using lineinfile module its very easy to update files on multiple hosts in a minute. To get more details about this module to kindly follow below link :
Ansible documentation: lineinfile – Manage lines in text files
Demo:
Following is our server setup of ansible:
Ansible controller:
Hostname: ansiblecontroller ip: 192.168.1.216
Targets :(where we are doing updates)
Hostname: target1 ip=192.168.1.217
Hostname: target2 ip t=192.168.1.218
Task:
To add line “nameserver 10.1.250.10” in “/etc/resolv.conf” on servers.
Make sure you have installed ansible package on the ansible controller host. if you are not please follow this article for installing ansible.
Steps: Add line in file on multiple servers using Ansible
- Create the ansilble inventory file which details out about the target machines as below. This is according my setup. Please tweak this according to your ip and hostnames.
$ cat inventory.txt target1 ansible_host=192.168.1.217 target2 ansible_host=192.168.1.218
- Now we create playbook file “ansible-add-line.yml” with following contents;
$ cat ansible-add-line.yml
$ cat ansible-add-line.yml - name: Adding new line in /etc/reslove.conf lineinfile hosts: all become: yes tasks: - name: Update entry into /etc/resolv.conf lineinfile: path: /etc/resolv.conf line: 'nameserver 10.1.250.10'
Make sure the file is indented properly otherwise you may get a error while excution. Please check proper format of yml file from my ide.
Execution:
Now on the ansible controller use below command for performing task:
ansible-playbook ansible-add-line.yml -i inventory.txt
OUTPUT:
Now you can able to see the output of “changed” parameter equals to “1” , that means we have successfully added the line “nameserver 10.1.250.10” in “/etc/resolv.conf” on servers.
Verification:
Target1:
[root@target1 ~]# cat /etc/resolv.conf # Generated by NetworkManager nameserver 103.14.232.100 nameserver 8.8.8.8 nameserver 192.168.1.1 nameserver 10.1.250.10 [root@target1 ~]#
Target2:
[root@target2 ~]# cat /etc/resolv.conf # Generated by NetworkManager nameserver 103.14.232.100 nameserver 8.8.8.8 nameserver 192.168.1.1 nameserver 10.1.250.10
This completes our task to add line in file on multiple servers using Ansible.
Leave a Reply