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
Following is our server setup of ansible:
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
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.
Now on the ansible controller use below command for performing task:
ansible-playbook ansible-add-line.yml -i inventory.txt
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.
[[email protected] ~]# cat /etc/resolv.conf # Generated by NetworkManager nameserver 18.104.22.168 nameserver 22.214.171.124 nameserver 192.168.1.1 nameserver 10.1.250.10 [[email protected] ~]#
[[email protected] ~]# cat /etc/resolv.conf # Generated by NetworkManager nameserver 126.96.36.199 nameserver 188.8.131.52 nameserver 192.168.1.1 nameserver 10.1.250.10
This completes our task to add line in file on multiple servers using Ansible.
The post Awesome way to add line in file on multiple servers using Ansible playbook in minutes appeared first on UX Techno.