Skip to content

Instantly share code, notes, and snippets.

@ei-grad
Created May 16, 2024 09:45
Show Gist options
  • Save ei-grad/8d7beb5ab330d5d550b76a51d8d9419b to your computer and use it in GitHub Desktop.
Save ei-grad/8d7beb5ab330d5d550b76a51d8d9419b to your computer and use it in GitHub Desktop.
#!/bin/bash
# Usage: tfe-api <endpoint> [<jq filter>]
set -euo pipefail
if [ $# -lt 1 ] || [ -z "${TF_TOKEN_app_terraform_io:-}" ]; then
[ $# -lt 1 ] && echo "Usage: tfe-api <endpoint> [<jq filter>]" >&2
[ -z "${TF_TOKEN_app_terraform_io:-}" ] && echo "TF_TOKEN_app_terraform_io is not set" >&2
exit 1
fi
RESOURCE="$1"
RESPONSE=""
NEXT_PAGE=""
while true; do
if [ -n "$NEXT_PAGE" ]; then
PAGE_ARGS=( "--url-query" "page[number]=$NEXT_PAGE" )
else
PAGE_ARGS=( )
fi
RESPONSE="$(
curl -s "https://app.terraform.io/api/v2/$RESOURCE" \
-H "Authorization: Bearer $TF_TOKEN_app_terraform_io" \
"${PAGE_ARGS[@]}"
)"
if [ "$(jq -r '.data | type' <<< "$RESPONSE")" == "array" ]; then
JQ_FILTER=".data[]"
else
JQ_FILTER=".data"
fi
if [ "$(jq -r 'has("included")' <<< "$RESPONSE")" == "true" ]; then
JQ_FILTER="${JQ_FILTER},.included[]"
fi
if [ $# -eq 2 ]; then
JQ_FILTER="$JQ_FILTER | $2"
fi
# on error, print error message and exit
if [ "$(jq 'has("errors")' <<< "$RESPONSE")" == "true" ]; then
jq '.' <<< "$RESPONSE" >&2
exit 1
fi
# if pages more than 1, print page info
if [ "$(jq -r '.meta | has("pagination")' <<< "$RESPONSE")" == "true" ]; then
jq -r '.meta.pagination | "# Page " + (."current-page"|tostring) + " of " + (."total-pages"|tostring)' <<< "$RESPONSE" >&2
fi
jq -r "$JQ_FILTER" <<< "$RESPONSE"
NEXT_PAGE="$(jq -r '.meta.pagination."next-page"' <<< "$RESPONSE")"
if [ "$NEXT_PAGE" == "null" ]; then
break
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment