Skip to content

Instantly share code, notes, and snippets.

@RichardBronosky
Last active April 12, 2018 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RichardBronosky/abe1652c2d5c78c35b92ad02bdf0d0af to your computer and use it in GitHub Desktop.
Save RichardBronosky/abe1652c2d5c78c35b92ad02bdf0d0af to your computer and use it in GitHub Desktop.
Update a DNS zone file with AWK
#!/bin/bash
usage(){
cat <<EOF
Usage: $(basename $0) zone_file record_type hostname ip_address
EOF
}
if [[ $# -lt 4 ]]; then
usage
exit 255
fi
zone_file="$1"
record_type="$2"
hostname="$3"
ip_address="$4"
args="${AWK_ARGS:-}"
if ! [[ -f $zone_file ]]; then
usage
echo "ERROR: zone_file '$zone_file' does not exist"
exit 1
fi
if [[ $hostname == ${hostname%.*.} ]]; then
usage
echo "ERROR: hostname '$hostname' does not match pattern 'host.tld.'"
exit 2
fi
temp=$(mktemp)
awk $args -v FS='\t' -v OFS='\t' -v record_type=$record_type -v hostname=$hostname -v ip_address=$ip_address '
$1==hostname && $3==record_type {$4=ip_address}
{print}
' $zone_file > $temp
diff $zone_file $temp
if [[ $? == 0 ]]; then
echo "No changes"
else
[[ "$(read -e -p 'Apply this change? [y/N]> '; echo $REPLY)" == [Yy]* ]] && cat $temp > $zone_file
# This next line is pretty specific to my env. You can remove it.
[[ $? == 0 ]] && echo -e "Now consider doing:\n sudo docker exec -it dns rndc reload ies"
fi
rm $temp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment