DNS is one of the most important components of web hosting. It resolves addresses which allows websites to be accessed online via domain names and emails to be sent/received.
Due to this importance, we decided to consolidate our DNS to 3 powerful name servers. Our task was split into 2 parts:
1. Updating the name servers in zone files.
2. Updating the name servers on the domains.
Name server update on the domain was not difficult as this is provided for in registry portals.
As for the zone files, we needed to develop a script to accomplish this. We needed the script to replace the current existing 2 name servers with 2 new ones, then add a third one as we now used three name servers to provide enough redundancy. All our name servers run on BIND.
Below is the script we developed to accomplish the task.
Note: Before running this script, please backup your zone files directory just in case of anything. One can never under estimate the importance of a backup!
#!/bin/bash
#Bash script to update nameservers
for file in *.db; do
base=$(basename "$file" '.db')
sed -i "s/ns1.domain.com/ns1.newdomain.com/g" /var/named/$file
sed -i "s/ns2.domain.com/ns2.newdomain.com/g" /var/named/$file
sed -i '/ns2.newdomain.com/a '$base.' 86400 IN NS ns3.newdomain.com.' /var/named/$file
done
The Script Explained
Basically, the following is what the script does. It should be run from inside the folder where zone files are stored.
– It loops through all files that end with .db e.g. adomain.com.db
– Anytime it opens a file:
– It finds any instance of the first name server, ns1.domain.com, and replaces with a new one ns1.newdomain.com. This is repeated for ns2.domain.com as well.
– With the two original domains replaced, a third one needs to be added. So line 8 in the script adds the third name server, ns3.newdomain.com, below the line that has ns2.newdomain.com
The option -i given to sed command makes sed write the changes to the file. Otherwise, it just displays the file with the changes but doesn’t save them on file.
The process above is repeated for all zone files.
After that, you need to reload daemons and restart named.
[root@serv0-wal named]# systemctl daemon-reload
[root@serv0-wal named]# systemctl restart named