Created
January 6, 2018 21:03
-
-
Save sciguy16/108a59d9abd36b572cc31b713a725f21 to your computer and use it in GitHub Desktop.
script to update records on a powerdns server when called by isc-dhcpd
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# arguments are type, address, hardware, name | |
LOGFILE=/tmp/dns.log | |
SUFFIX=".clients.example.com." | |
APIKEY="SUPERsecretAPIkey" | |
APIPORT=8081 | |
APIADDRESS="10.0.0.1" | |
APIENDPOINT="/api/v1/servers/localhost/zones/example.com." | |
PTRENDPOINT="/api/v1/servers/localhost/zones/10.10.10.in-addr.arpa." | |
TYPE=$1 | |
ADDRESS=$2 | |
MAC=$3 | |
HOSTNAME="$4" | |
if [ "$HOSTNAME" == "none" ] | |
then | |
HOSTNAME="dhcp-${ADDRESS}" | |
fi | |
case $TYPE in | |
"commit") | |
### commit a new lease to the API | |
FQDN="${HOSTNAME}${SUFFIX}" | |
echo "adding entry ${FQDN}" | |
JSON=$( cat << END | |
{ "rrsets": [ | |
{ | |
"name": "${FQDN}", | |
"type": "A", | |
"ttl": 86400, | |
"changetype": "REPLACE", | |
"records": [ | |
{ | |
"content": "$ADDRESS", | |
"disabled": false, | |
"set-ptr": true | |
}] | |
} | |
]} | |
END | |
) | |
curl -H "X-API-Key: ${APIKEY}" -X PATCH --data "$JSON" http://${APIADDRESS}:${APIPORT}${APIENDPOINT} | |
;; | |
"release"|"expire") | |
echo "removing entry ${ADDRESS}" | |
### remove a dns entry | |
# look up the entry name via its PTR record | |
# piping through xargs strips the spaces :D | |
PTRNAME=$(nslookup $ADDRESS $APIADDRESS | grep name | cut -d'=' -f2 | xargs) | |
# verify that PTRNAME is vaguely valid | |
if [ "$PTRNAME" == " " ] ; then | |
# no result found, we probably shouldn't try to process it further | |
echo "PTR not found" | |
exit 1 | |
fi | |
# sanity check on the length of PTRNAME to avoid deleting the entire | |
if [ $(echo "$PTRNAME" | wc -c) -lt 2 ] ; then | |
# name is too short | |
echo "name $PTRNAME too short" | |
exit 1 | |
fi | |
### remove the A record | |
echo "ptr name is $PTRNAME" | |
JSON=$( cat << END | |
{ "rrsets": [ | |
{ | |
"name": "$PTRNAME", | |
"type": "A", | |
"changetype": "DELETE" | |
} | |
]} | |
END | |
) | |
echo $JSON | json | |
curl -H "X-API-Key: ${APIKEY}" -X PATCH --data "$JSON" http://$APIADDRESS:$APIPORT$APIENDPOINT | |
### remove the PTR record | |
PTRID="$(printf '%s.' $ADDRESS | tac -s.)in-addr.arpa." | |
JSON=$( cat << END | |
{ "rrsets": [ | |
{ | |
"name": "$PTRID", | |
"type": "PTR", | |
"changetype": "DELETE" | |
} | |
]} | |
END | |
) | |
echo $JSON | json | |
curl -H "X-API-Key: ${APIKEY}" -X PATCH --data "$JSON" http://$APIADDRESS:$APIPORT$PTRENDPOINT | |
;; | |
esac | |
echo "`date` ${TYPE} $ADDRESS $MAC $HOSTNAME" | tee -a $LOGFILE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment