Skip to content

Instantly share code, notes, and snippets.

@sciguy16
Created January 6, 2018 21:03
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 sciguy16/108a59d9abd36b572cc31b713a725f21 to your computer and use it in GitHub Desktop.
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
#!/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