Write a shell script that adds...
Write a shell script that adds, updates, or deletes DNS records to the NSD service, based on an input CSV file. The CSV file will only have a list of DNS records and not an action (add, delete, update) to it, the script needs to get a list of current DNS records in NSD, compare them with the CSV file and determine whether to add, update, or delete DNS records.
Here's an example shell script that adds, updates, or deletes DNS records to the NSD service based on an input CSV file:
#!/bin/bash
# Set variables
CSV_FILE="/path/to/csv/file"
ZONE_NAME="example.com"
NSD_CONTROL="/usr/sbin/nsd-control"
# Get list of current DNS records from NSD
NSD_ZONE=$($NSD_CONTROL dumpzone $ZONE_NAME)
# Loop through CSV file
while IFS=, read -r RECORD_NAME RECORD_TYPE RECORD_VALUE; do
# Check if record exists in NSD zone
if [[ "$NSD_ZONE" =~ (^|[[:space:]])"$RECORD_NAME[[:space:]]+([[:digit:]]+)[[:space:]]+IN[[:space:]]+$RECORD_TYPE[[:space:]]+$RECORD_VALUE($|[[:space:]])" ]]; then
# Update existing record
$NSD_CONTROL editzone $ZONE_NAME update $RECORD_NAME $RECORD_TYPE $RECORD_VALUE
else
# Add new record
$NSD_CONTROL editzone $ZONE_NAME add $RECORD_NAME $RECORD_TYPE $RECORD_VALUE
fi
done < "$CSV_FILE"
# Delete records that are not in the CSV file
for RECORD_NAME in $(grep -oP '(?<=\A)[^,]+' $CSV_FILE); do
if [[ ! "$NSD_ZONE" =~ (^|[[:space:]])"$RECORD_NAME[[:space:]]+([[:digit:]]+)[[:space:]]+IN[[:space:]]+[[:upper:]]+($|[[:space:]])" ]]; then
# Delete record
$NSD_CONTROL editzone $ZONE_NAME del $RECORD_NAME
fi
done
Here is how to use the script:
- Replace the
CSV_FILEvariable with the path to your input CSV file. - Replace the
ZONE_NAMEvariable with the name of your DNS zone. - Replace the
NSD_CONTROLvariable with the path to yournsd-controlbinary. - Set execute permission for the script:
chmod +x /path/to/script.sh - Run the script:
/path/to/script.sh
The script will loop through each line of the CSV file and determine whether to add, update, or delete DNS records based on the comparison with the current DNS records in NSD. The script will add new records, update existing records, and delete records that are not in the CSV file.