Skip to content

Instantly share code, notes, and snippets.

@chorn
Created April 4, 2016 10:44
Show Gist options
  • Save chorn/871eea5628c2ad86c92621cf2e510e63 to your computer and use it in GitHub Desktop.
Save chorn/871eea5628c2ad86c92621cf2e510e63 to your computer and use it in GitHub Desktop.
#!/bin/bash
declare API
API="https://api.dnsimple.com/v2"
declare _zone
_zone="$1"
declare _record
_record="$2"
declare _ip
_ip="$3"
if [[ -z "$DNSIMPLE_ACCOUNT_TOKEN" ]] ; then
echo "You must create a 'User access token' on your dnsimple.com User Settings page."
echo "The new ACCOUNT token must be defined as \$DNSIMPLE_ACCOUNT_TOKEN in your environment."
exit 1
fi
if ! command -v jq >&/dev/null ; then
echo "You need to have 'jq' installed and in your $PATH."
echo "https://stedolan.github.io/jq/"
exit 1
fi
if [[ -z "$_zone" ]] ; then
echo "Specify which zone (domain name) you want to use."
exit 1
fi
if [[ -z "$_record" ]] ; then
echo "Specify which hostname you want to create/update."
exit 1
fi
if [[ -z "$_ip" ]] ; then
_ip=$(dig +short myip.opendns.com @resolver1.opendns.com || curl -f4L http://ifconfig.me/ || curl -f4L http://icanhazip.com/)
fi
if [[ -z "$_ip" ]] ; then
echo "No IP to use has been defined, setting it automatically doesn't work right now."
exit 1
fi
dnsimple_api() {
local _resource="$1"
curl -sS \
-H "Authorization: Bearer ${DNSIMPLE_ACCOUNT_TOKEN}" \
-H 'Accept: application/json' \
"${API}/${_resource}?per_page=100&page=1"
}
dnsimple_api_payload() {
local _resource="$1"
local _method="$2"
local _json="$3"
curl -sS \
-H "Authorization: Bearer ${DNSIMPLE_ACCOUNT_TOKEN}" \
-H 'Accept: application/json' \
-H "Content-Type: application/json" \
-X "${_method}" \
-d "${_json}" \
"${API}/${_resource}"
}
if [[ -z "$DNSIMPLE_ACCOUNT_ID" ]] ; then
DNSIMPLE_ACCOUNT_ID=$(dnsimple_api "whoami" | jq '.data.account.id')
export DNSIMPLE_ACCOUNT_ID
fi
zones() {
dnsimple_api "${DNSIMPLE_ACCOUNT_ID}/domains" | jq '.'
}
zone_info() {
dnsimple_api "${DNSIMPLE_ACCOUNT_ID}/zones/${_zone}" | jq '.'
}
zone_records() {
dnsimple_api "${DNSIMPLE_ACCOUNT_ID}/zones/${_zone}/records" | jq '.'
}
zone_record_id() {
dnsimple_api "${DNSIMPLE_ACCOUNT_ID}/zones/${_zone}/records" | jq ".data[] | select(.name == \"${_record}\").id"
}
declare _id
_id=$(zone_record_id)
send_zone_record() {
local _method="$1"
dnsimple_api_payload "${DNSIMPLE_ACCOUNT_ID}/zones/${_zone}/records" "${_method}" "{\"name\":\"${_record}\",\"type\":\"A\",\"content\":\"${_ip}\"}" | jq '.'
}
if [[ -z "$_id" ]] ; then
send_zone_record POST
else
send_zone_record PATCH
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment