Created
November 5, 2019 06:35
-
-
Save triangletodd/70b27e41a7071521afa0c1854b39111c to your computer and use it in GitHub Desktop.
Bash functions for interacting with the Cloudflare v4 API
This file contains hidden or 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
#!/usr/bin/env bash | |
export CF_CURL_OPTS=() | |
export CF_V4_API='https://api.cloudflare.com/client/v4' | |
_cf_exit() { | |
# if being called directly, don't exit | |
if [ ${#FUNCNAME[@]} -eq 0 ]; then | |
return 1 | |
fi | |
exit 1 | |
} | |
cf_auth() { | |
if [[ -n $CLOUDFLARE_API_TOKEN ]]; then | |
CF_CURL_OPTS=( -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" ) | |
elif [[ -z $CLOUDFLARE_API_KEY ]] && [[ -z $CLOUDFLARE_EMAIL ]]; then | |
printf 'Unable to find CLOUDFLARE_API_TOKEN or CLOUDFLARE_API_KEY + CLOUDFLARE_EMAIL. Please see:\n' | |
printf ' https://support.cloudflare.com/hc/en-us/articles/200167836-Managing-API-Tokens-and-Keys\n' | |
printf ' https://www.terraform.io/docs/providers/cloudflare/index.html\n' | |
_cf_exit || return 1 | |
else | |
CF_CURL_OPTS=( -H "X-Auth-Email: $CLOUDFLARE_EMAIL" -H "X-Auth-Key: $CLOUDFLARE_API_KEY" ) | |
fi | |
export CF_CURL_OPTS | |
} | |
cf_get() { | |
if ! cf_auth; then return 1; fi | |
local ep="$1" | |
shift | |
local params | |
local resp | |
if [[ $# -gt 0 ]]; then | |
params+='?' | |
fi | |
for param in "$@"; do | |
if [[ $params == '?' ]]; then | |
params+="${param}" | |
else | |
params+='&' | |
params+="${param}" | |
fi | |
done | |
resp="$(curl -s "${CF_CURL_OPTS[@]}" -X GET "${CF_V4_API}/${ep}${params}")" | |
success="$(jq -crj '.success' <<< "$resp")" | |
if [[ $success == 'true' ]]; then | |
printf '%s' "$resp" | |
else | |
jq -crj '.errors' <<< "$resp" | |
_cf_exit || return 1 | |
fi | |
} | |
cf_get_all() { | |
local ep="$1" | |
shift | |
local -i page=1 | |
local per_page="${CF_PER_PAGE:-20}" | |
local resp | |
local count | |
local resources | |
while true; do | |
if resp="$(cf_get "${ep}" "page=${page}" "per_page=${per_page}" "$@")"; then | |
count="$(jq -crj '.result_info.count' <<< "$resp")" | |
resources+="$(jq -crj '.result[]' <<< "$resp")" | |
if [[ $count -lt $per_page ]]; then break; fi | |
(( page++ )) | |
continue | |
else # cf_get returned non-0 | |
printf '%s' "$resp" | |
_cf_exit || return 1 | |
fi | |
done | |
echo "$resources" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment