Skip to content

Instantly share code, notes, and snippets.

@trnila
Created June 2, 2018 07:10
Show Gist options
  • Save trnila/81d8e5e53ce7480b5079e8dcc4d4437a to your computer and use it in GitHub Desktop.
Save trnila/81d8e5e53ce7480b5079e8dcc4d4437a to your computer and use it in GitHub Desktop.
Update cloudflare DNS zone in your editor
#!/bin/sh
history_dir=~/.cloudflare/dns_history
auth_email=$(awk -F = '/email/ {print $2}' ~/.cloudflare/cloudflare.cfg)
auth_key=$(awk -F = '/token/ {print $2}' ~/.cloudflare/cloudflare.cfg )
zone_name=$1
zone_file="$history_dir/$zone_name"
if [ -z "$zone_name" ]; then
echo "Usage: $0 zone.tld"
exit 1
fi
if [ -z "$auth_email" ] || [ -z "$auth_key" ]; then
echo "Configuration missing"
echo
echo "# ~/.cloudflare/cloudflare.cfg"
echo "[CloudFlare"]
echo "email=..."
echo "token=..."
exit 1
fi
cf_api() {
method=$1
url_target=$2
shift
shift
curl -s -X "$method" "https://api.cloudflare.com/client/v4/$url_target" \
-H "X-Auth-Email: $auth_email" \
-H "X-Auth-Key: $auth_key" \
"$@"
}
git_cmd() {
git --git-dir "$history_dir/.git" --work-tree "$history_dir" "$@"
}
show() {
if command -v jq > /dev/null; then
jq
fi
cat
}
if [ ! -d "$history_dir" ]; then
mkdir -p "$history_dir" || exit 1
fi
if [ ! -d "$history_dir/.git" ]; then
git init "$history_dir"
fi
zone_id=$(cf_api GET "zones?name=$zone_name" | grep -Po '(?<="id":")[^"]*' | head -1)
# get and commit current zone
cf_api GET "zones/$zone_id/dns_records/export" > "$zone_file"
git_cmd add "$zone_name"
git_cmd commit -m "Before edit $zone_name"
# open editor
"$EDITOR" "$zone_file"
# update zone on cf if file modified
if git_cmd ls-files -m | grep "^$zone_name$"; then
git_cmd add "$zone_name"
git_cmd commit -m "After edit $zone_name"
cf_api POST "zones/$zone_id/dns_records/import" --form "file=@$zone_file;proxied=false" | show
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment