Sub topic 14
Handling credentials safely
This chapter assumes you can already authenticate the CLI, use profiles and environment variables, and call the REST API with a bearer token. It covers how to keep those credentials from leaking, and how to limit the damage if one does.
What you are protecting
Every automation tool in this tutorial ends up sending a bearer token to your workspace. Anyone who holds that token can do what its owner can do until it expires or is revoked. Credential handling comes down to three questions:
- Which identity should the automation run as?
- Where is the secret stored, and who can read it?
- How long does it stay valid?
Choose the right credential type
| Credential | Identity | Lifetime | Typical use |
|---|---|---|---|
| OAuth user-to-machine (`databricks auth login`) | A person | Short-lived access token, refreshed by the CLI | Interactive work on your laptop |
| OAuth machine-to-machine (client ID and secret) | A service principal | Access tokens last about one hour and are re-requested automatically | Scheduled scripts and CI/CD |
| Personal access token (PAT) | A person or a service principal | Set when created, and can be unlimited | Tools that support only a static token |
A service principal is an identity for automation. It is not tied to a person, so the automation keeps working when someone leaves the team. Its permissions can be set separately from any user's.
Prefer OAuth over a PAT where the tool allows it. An OAuth access token expires on its own, so a leaked one is useful for a short time. A PAT with no expiry is useful until someone finds and revokes it.
Use a service principal with least privilege
Least privilege means the identity has only the permissions the task needs. A deployment pipeline that runs one job does not need workspace admin rights.
A workable setup:
- Create one service principal per pipeline or environment, for example one for dev and one for prod. A leak in dev then cannot touch prod.
- Give it access only to what it uses. That usually means permission to manage or run the specific jobs, plus read access to the notebooks or files it deploys.
- Generate an OAuth secret for it in the account console or workspace admin settings. Copy the secret when it is shown, because you cannot read it again later.
- Give the secret an expiry and a rotation date.
The CLI and SDK read the service principal's credentials from environment variables:
export DATABRICKS_HOST="https://<workspace-host>"
export DATABRICKS_CLIENT_ID="<service-principal-application-id>"
export DATABRICKS_CLIENT_SECRET="<oauth-secret>"
databricks current-user meThe output of current-user me shows the service principal, not you. Run it first in any new environment to confirm which identity the automation really uses.
Keep secrets out of the places they leak from
Credentials leak less through attacks than through ordinary habits. These are the common ones.
Source control
Never commit a token, a client secret, or a .databrickscfg file. Add the following to .gitignore and check it before the first commit:
printf '%s\n' '.databrickscfg' '.env' '*.secret' >> .gitignore
git check-ignore -v .envIf a secret was committed, deleting it in a later commit is not enough, because it stays in the history. Revoke the credential first, then clean the history if needed.
The profile file
databricks auth login writes to ~/.databrickscfg. OAuth profiles store the host and settings, not long-lived secrets. A profile with a PAT stores the token in plain text. Restrict the file to your own user:
chmod 600 ~/.databrickscfg
ls -l ~/.databrickscfgThe command line
Arguments on a command line can appear in the process list (ps) and in shell history. A typical mistake is pasting the token into a curl header:
# Avoid: the token is visible in the process list and shell history
curl -H "Authorization: Bearer dapiXXXXXXXX" "$DATABRICKS_HOST/api/2.1/jobs/list"Reading the token from an environment variable keeps it out of your history, but the expanded value is still an argument to curl. A safer pattern passes the header through standard input as a curl config. printf is a shell builtin, so the token does not appear as a process argument:
printf 'header = "Authorization: Bearer %s"\n' "$DATABRICKS_TOKEN" \
| curl -sS -K - "$DATABRICKS_HOST/api/2.1/jobs/list"The simplest fix is to use the CLI or the SDK, which read credentials from the environment and never put them on a command line.
Logs
Two habits cause most log leaks:
set -xin a shell script prints every command after variable expansion, including any token inside it. Do not turn it on in scripts that handle credentials. If you must, wrap the sensitive section inset +xandset -x.- Printing a full request, response, or exception can expose headers. Log the HTTP status code and the response body, not the request headers.
CI systems mask values stored as secrets, but masking matches exact strings. A secret that is transformed first, for example base64-encoded, may not be masked.
Store secrets where they can be controlled
| Where the automation runs | Where to keep the secret |
|---|---|
| Your laptop | OAuth login, which needs no stored secret. Otherwise an OS keychain or a password manager. |
| CI/CD pipeline | The CI system's encrypted secrets store, exposed to the job as environment variables |
| A server or scheduler | A secrets manager such as AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault |
| Code running inside Databricks | A Databricks secret scope, read with `dbutils.secrets.get` |
Databricks secret scopes hold secrets that your notebooks and jobs need at run time, such as a password for an external database. The CLI manages them:
databricks secrets create-scope pipeline-secrets
databricks secrets put-secret pipeline-secrets db-passwordThe put-secret command prompts for the value, so it does not appear in your history. Databricks redacts secret values if a notebook prints them, but redaction is not a security boundary. Anyone who can run code with access to the scope can get the value out. Control access to the scope itself.
Pass credentials through the SDK without handling them
The SDK finds credentials on its own, so your code never mentions a secret. This code is safe to commit:
from databricks.sdk import WorkspaceClient
w = WorkspaceClient() # reads DATABRICKS_HOST and the client ID and secret from the environment
me = w.current_user.me()
print(f"Running as: {me.user_name}")If the code fails because of missing credentials, the error message names what is missing. It does not print secret values.
Limit the blast radius and plan for rotation
Assume a credential will eventually leak and make the cleanup cheap.
- Separate identities. One service principal per pipeline and environment means you revoke one thing, not everything.
- Short expiry. Set an expiry on every PAT and OAuth secret. A calendar reminder to rotate them is better than none.
- Rotate without downtime. A service principal can hold more than one secret. Create the new secret, update the secret store, confirm the pipeline works, then delete the old secret.
- Audit. List the tokens that exist and remove those nobody recognizes:
databricks tokens listThis lists your own PATs. Workspace admins can review and revoke tokens for other users through the token management commands or the admin settings.
- Revoke on suspicion. If a secret appears in a log, a commit, or a chat message, treat it as compromised and rotate it. Do not wait to see whether anyone used it.
Avoid long-lived secrets in CI altogether
Some CI platforms can prove their identity to Databricks without a stored secret. GitHub Actions, for example, can issue a short-lived OpenID Connect (OIDC) token for each run, and Databricks can exchange it for an access token if you configure a federation policy for the service principal. Then there is no secret in the CI settings to leak. The next chapters on CI/CD cover the pipeline itself. Check the Databricks documentation for the platforms and settings it currently supports before relying on this.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `401` or "Invalid access token" | The token expired, was revoked, or is for a different workspace | Re-authenticate, or generate a new secret and check `DATABRICKS_HOST` |
| `403` "does not have permission" | The identity is valid but lacks access to the resource | Grant the service principal the specific permission. Do not make it an admin. |
| Script works on your laptop, fails in CI | Your laptop used a profile or OAuth login that CI does not have | Set the environment variables in CI and run `databricks current-user me` as a first step |
| The wrong identity acts | A profile or `DATABRICKS_TOKEN` takes precedence over what you expected | Check `current-user me` and unset stray variables |
| A token appears in CI logs | `set -x`, verbose output, or an echoed variable | Remove the output, rotate the token, and re-run |
Checklist
- The identity is a service principal for anything unattended.
- It has only the permissions the task needs.
- Secrets live in a secrets store, not in code,
.envfiles in the repository, or chat. - Tokens and secrets have an expiry and a rotation plan.
- Scripts never print credentials, and the first step of each run confirms the identity.
Exercise
A teammate's deployment script runs curl -H "Authorization: Bearer $DATABRICKS_TOKEN" ... in CI with set -x enabled. The token is a PAT with no expiry, owned by the teammate's personal account. Name three problems and the fix for each.
Show answer
(1) set -x prints the command after expansion, so the token appears in the CI logs. Remove set -x from that section, or wrap it in set +x, and rotate the token because it has already been logged. (2) The token is a PAT with no expiry, so a leak stays useful indefinitely. Use OAuth with a service principal, or at least set an expiry on the token. (3) The token belongs to a person, so the pipeline breaks when they leave and runs with all of their permissions. Create a service principal with only the permissions the pipeline needs and use its credentials instead. Passing the token as a curl argument also exposes it in the process list, so use the CLI or SDK, or pass the header through curl -K -.