Skip to content

Instantly share code, notes, and snippets.

@macoril
Created July 27, 2020 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macoril/ef864d5a6a1bef237cc3f7e559568740 to your computer and use it in GitHub Desktop.
Save macoril/ef864d5a6a1bef237cc3f7e559568740 to your computer and use it in GitHub Desktop.
metabaseのAPIを実行するシェルスクリプト。セッションが死んでたら取得し直す。
#!/bin/bash
# usage:
# . ./metabase_api_exe.sh [HTTP method] [path]
# sample:
# . ./metabase_api_exe.sh GET /api/pulse
urlbase='http://path.to.your.metabase'
username='your_account@example.com'
password='your_password'
if [[ $urlbase == "" ]] ; then
echo "need to set a url of your metabase."
return 0
fi
method=$1
url=$urlbase$2
while :
do
# 指定のAPIを実行する
curl_result=$( \
curl -s -X $method \
-H "Content-Type: application/json" \
-H "X-Metabase-Session: $session" \
$url \
)
if [[ $curl_result == "" ]] ; then
cat <<EOS
usage:
. ./metabase_api_exe.sh [HTTP method] [path]
sample:
. ./metabase_api_exe.sh GET /api/pulse
EOS
break
# session 切れの場合は取得し直す
elif [[ $curl_result = 'Unauthenticated' ]]; then
url2=$urlbase'/api/session'
json="'{\"username\" : \"$username\", \"password\" : \"$password\"}'"
echo "You are ${curl_result}, need to get an active session id."
if [[ $username == "" || $password == "" ]] ; then
echo "But you haven't set your username and/or password."
echo "If you want to get a new session id,"
echo "please set your username and password."
return 0
fi
read -p "Are you going to get a new one? (y/n): " yn
case "$yn" in
[yY]*)
;;
*)
echo "abort."
return 0
;;
esac
a=$(eval $(cat <<EOS
curl -s -X POST
-H "Content-Type: application/json"
-d $json $url2
EOS
))
export session=$(echo $a | jq '.id' | tr -d \")
echo "new session id is: $session"
echo ""
# 結果を出力して終了
else
echo $curl_result
break
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment