Sub topic 2
Scripting with JSON Output and jq
Assume you know basic shell commands, environment variables, JSON, HTTP requests, and Databricks jobs. This chapter shows how to combine the CLI, REST API, and jq in scripts.
Process CLI Output with jq
Use JSON output when another command or script must consume Databricks data. For example:
databricks jobs list --output json |
jq -r '.[] | "\(.job_id)\t\(.settings.name)"'The pipe sends the JSON to jq. The filter selects each job and prints its ID and name as tab-separated values. This is more reliable than parsing formatted terminal output.
Call the Jobs REST API
A REST API exposes resources through HTTP paths. A Databricks workspace host identifies the workspace, and a path identifies the operation. A bearer token authenticates the request.
export DATABRICKS_HOST="https://<workspace-host>"
export DATABRICKS_TOKEN="<token>"
curl -sS -X POST "$DATABRICKS_HOST/api/2.1/jobs/run-now" \
-H "Authorization: Bearer $DATABRICKS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"job_id":123}'The response contains a run_id. Save it and use it to monitor the run.
run_id=$(curl -sS -X POST "$DATABRICKS_HOST/api/2.1/jobs/run-now" \
-H "Authorization: Bearer $DATABRICKS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"job_id":123}' | jq -r '.run_id')
while :; do
state=$(curl -sS "$DATABRICKS_HOST/api/2.1/jobs/runs/get?run_id=$run_id" \
-H "Authorization: Bearer $DATABRICKS_TOKEN" | jq -r '.state.life_cycle_state')
case "$state" in
TERMINATED|SKIPPED|INTERNAL_ERROR) break ;;
esac
sleep 15
done
echo "$state"Use the CLI API Command
When a dedicated CLI command does not exist, call an endpoint directly:
databricks api get /api/2.1/jobs/listFor requests with a body, provide JSON using the command's request-body option supported by your CLI version.
Handle Pages and Failures
List endpoints can return a page token. Continue requesting pages with page_token until next_page_token is absent. Check HTTP status codes before parsing a response. A 401 or 403 usually indicates authentication or permission problems. A 404 often means the path or workspace is wrong. A 429 means rate limiting; wait for the Retry-After value, then retry with backoff.
Exercise
Why should a script inspect an API response's HTTP status before passing its body to jq?
Show answer
An error response may have a different JSON shape, so parsing it as a successful response can hide authentication, permission, path, or rate-limit failures.