Skip to content

Instantly share code, notes, and snippets.

@jimyang2008
Last active December 19, 2023 11:41
Show Gist options
  • Save jimyang2008/4e3e0cafdf3afa6021c14c52ef03ff71 to your computer and use it in GitHub Desktop.
Save jimyang2008/4e3e0cafdf3afa6021c14c52ef03ff71 to your computer and use it in GitHub Desktop.
cf-api.sh
#!/bin/bash
err() {
echo "ERROR: $@" >&2
}
cf_api() {
action=$1; shift
context=$1; shift
curl -Lks --request $action \
--url https://api.cloudflare.com/client/v4/$context \
--header "Authorization: Bearer $API_TOKEN" \
--header 'Content-Type: application/json' \
--header "X-Auth-Email: $API_TOKEN" \
"$@"
}
cf_get() {
cf_api GET $1
}
list_zones() {
cf_get zones
}
list_dns_records() {
cf_get zones/$ZONE_ID/dns_records
}
create_dns() {
dname=$1; shift
dtype=$1; shift
dcontent=$1; shift
dproxied=${1-false}; shift
cf_api POST zones/$ZONE_ID/dns_records --data "$(cat <<EOS
{
"name": "$dname",
"type": "$dtype",
"content": "$dcontent",
"proxied": $dproxied,
"comment": "Domain verification record at $(date)",
"ttl": 3600
}
EOS
)"
}
update_dns() {
dname=$1; shift
dtype=$1; shift
dcontent=$1;shift
read rid rcontent <<<$( list_dns_records| jq -r ".result[]|select(.name ==\"$dname\")|[.id,.content]|@tsv" )
test "$rcontent" == "$dcontent" || \
cf_api PUT zones/$ZONE_ID/dns_records/$rid --data "$(cat <<EOS
{
"content": "$dcontent",
"name": "$dname",
"proxied": false,
"type": "$dtype",
"comment": "Updated via API at $(date -u)",
"ttl": 3600
}
EOS
)"
}
test -n "$API_TOKEN" || {
err "API_TOKEN not defined"
exit 1
}
ZONE_ID=$(list_zones| jq -r '.result[0].id')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment