Skip to content

Manage Secrets and Credentials

Secure configuration management for database credentials, storage access keys, and other sensitive settings.

Overview

DataJoint separates configuration into sensitive and non-sensitive components:

Component Location Purpose Version Control
Non-sensitive datajoint.json Project settings, defaults โœ… Commit to git
Sensitive .secrets/ directory Credentials, API keys โŒ Never commit
Dynamic Environment variables CI/CD, production โš ๏ธ Context-dependent

Configuration Priority

DataJoint loads configuration in this priority order (highest to lowest):

  1. Programmatic settings โ€” dj.config['key'] = value
  2. Environment variables โ€” DJ_HOST, DJ_USER, DJ_STORES, etc.
  3. Project configuration โ€” datajoint.json
  4. Secrets directory โ€” .secrets/database.user, .secrets/database.password, .secrets/stores.<name>.<attr> (each fills a value the file and env didn't already set)
  5. Default values โ€” Built-in defaults

Higher priority sources override lower ones, with one limit on environment variables. They take precedence over datajoint.json only for DJ_HOST, DJ_USER, DJ_PASS, DJ_PORT, DJ_BACKEND, DJ_DATABASE_NAME, DJ_DATABASE_PREFIX, DJ_CREATE_TABLES, DJ_LOG_LEVEL, DJ_STORES and the diagram display settings. For other settings, including database.use_tls (DJ_USE_TLS), a value in datajoint.json replaces the environment variable.

Set DJ_CONFIG_FILE (new in 2.3.6) to load one named configuration file with no search. Set DJ_IGNORE_CONFIG_FILE=true (new in 2.2.3) to skip both datajoint.json and the secrets directory entirely โ€” see Env-var-only deployments below.

.secrets/ Directory Structure

Create a .secrets/ directory in your project root:

project/
โ”œโ”€โ”€ datajoint.json               # Non-sensitive settings (commit)
โ”œโ”€โ”€ .gitignore                   # Must include .secrets/
โ”œโ”€โ”€ .secrets/
โ”‚   โ”œโ”€โ”€ database.user            # Database credentials, one value per file
โ”‚   โ”œโ”€โ”€ database.password
โ”‚   โ”œโ”€โ”€ stores.main.access_key   # S3/cloud storage credentials
โ”‚   โ”œโ”€โ”€ stores.main.secret_key
โ”‚   โ”œโ”€โ”€ stores.archive.access_key
โ”‚   โ”œโ”€โ”€ stores.archive.secret_key
โ”‚   โ””โ”€โ”€ stores.uc.token          # any stores.<name>.<attr> (new in 2.2.4)
โ””โ”€โ”€ ...

New in 2.2.4

Any stores.<name>.<attr> file is loaded, not only access_key / secret_key. Plugin-registered storage adapters (e.g. a Databricks Bearer-token adapter) can define their own field names โ€” see Storage Adapter API.

Critical: Add .secrets/ to .gitignore:

# .gitignore
.secrets/

Database Credentials

Each secret is a separate plain-text file named for the setting it carries:

mkdir -p .secrets
echo "myuser"     > .secrets/database.user
echo "mypassword" > .secrets/database.password
chmod 600 .secrets/*

Non-sensitive database settings go in datajoint.json:

{
  "database.host": "db.example.com",
  "database.port": 3306,
  "database.use_tls": true,
  "safemode": true
}

For CI/CD and production environments:

export DJ_HOST=db.example.com
export DJ_USER=myuser
export DJ_PASS=mypassword
export DJ_PORT=3306
export DJ_USE_TLS=true

Option 3: Programmatic Configuration

For scripts and applications:

import datajoint as dj

dj.config['database.host'] = 'localhost'
dj.config['database.user'] = 'myuser'
dj.config['database.password'] = 'mypassword'

Security note: Only use this when credentials come from secure sources (environment, vault, secrets manager).

Object Storage Credentials

File Storage (No Credentials)

Local or network-mounted file systems don't require credentials:

{
  "stores": {
    "default": "main",
    "main": {
      "protocol": "file",
      "location": "/data/my-project"
    }
  }
}

S3/MinIO Storage (With Credentials)

Config in datajoint.json (non-sensitive)

{
  "stores": {
    "default": "main",
    "main": {
      "protocol": "s3",
      "endpoint": "s3.amazonaws.com",
      "bucket": "my-bucket",
      "location": "my-project/data"
    },
    "archive": {
      "protocol": "s3",
      "endpoint": "s3.amazonaws.com",
      "bucket": "archive-bucket",
      "location": "my-project/archive"
    }
  }
}

Credentials in .secrets/ directory

Create separate files for each store's credentials:

.secrets/stores.main.access_key
.secrets/stores.main.secret_key
.secrets/stores.archive.access_key
.secrets/stores.archive.secret_key

File format: Plain text, one credential per file:

# .secrets/stores.main.access_key
AKIAIOSFODNN7EXAMPLE

# .secrets/stores.main.secret_key
wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

No static keys? Use an ambient identity

On infrastructure with an AWS identity already attached โ€” an EC2 instance profile, EKS/IRSA service-account role, ECS task role, or SSO โ€” omit access_key and secret_key entirely. The AWS default credential chain resolves the identity (and refreshes it for long-running jobs), so no static keys need to be minted or stored. Set both only for static credentials.

Alternative: Environment Variables

New in 2.2.4

DJ_STORES carries a JSON-encoded copy of the entire stores dict, in the same shape as datajoint.json. Replaces the stores block from the file. .secrets/stores.<name>.<attr> files still fill in attributes that DJ_STORES omits.

For cloud deployments, put the entire stores block in a single env var:

export DJ_STORES='{
  "default": "main",
  "main": {
    "protocol": "s3",
    "endpoint": "s3.amazonaws.com",
    "bucket": "my-bucket",
    "location": "my-project/data",
    "access_key": "AKIAIOSFODNN7EXAMPLE",
    "secret_key": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
  }
}'

For plugin-registered adapters, the field names are whatever the adapter declares โ€” token, api_key, workspace_url, etc. See Storage Adapter API.

If DJ_STORES contains invalid JSON, DataJoint raises ValueError at config-load time with the JSON parser's error message.

Environment Variable Reference

Database Connections

Setting Environment Variable Description
database.host DJ_HOST Database hostname
database.port DJ_PORT Database port (default: 3306)
database.user DJ_USER Database username
database.password DJ_PASS Database password
database.use_tls DJ_USE_TLS Use TLS encryption (true/false)

Object Stores

Variable Description
DJ_STORES JSON-encoded stores dict (same shape as datajoint.json). Replaces the stores block from the file. (new in 2.2.4)

Config-Source Control

Variable Default Description
DJ_IGNORE_CONFIG_FILE false If true, skip datajoint.json, the project .secrets/, and /run/secrets/datajoint/. Only env vars and defaults apply. (new in 2.2.3)
DJ_CONFIG_FILE โ€” Path of the configuration file to load at import, with no search. The .secrets/ directory next to it is also used. A relative path is resolved against the working directory, and ~ is expanded. If the file does not exist, import datajoint raises FileNotFoundError. Ignored when DJ_IGNORE_CONFIG_FILE=true. (new in 2.3.6)

Env-var-only deployments

New in 2.2.4

DJ_IGNORE_CONFIG_FILE=true plus DJ_STORES gives a deployment a hard guarantee that no file on disk contributes to config โ€” only env vars do. This is how the DataJoint Platform configures pipelines.

For Kubernetes, Lambda, the DataJoint Platform, or any deployment where the container image must not carry configuration:

export DJ_IGNORE_CONFIG_FILE=true
export DJ_HOST=db.example.com
export DJ_USER=$(vault read -field=username secret/datajoint)
export DJ_PASS=$(vault read -field=password secret/datajoint)
export DJ_STORES="$(vault read -format=json -field=stores secret/datajoint)"

With DJ_IGNORE_CONFIG_FILE=true, DataJoint skips:

  • the recursive parent-directory search for datajoint.json
  • the project .secrets/ directory
  • the Docker/Kubernetes /run/secrets/datajoint/ directory

Only env vars (DJ_HOST, DJ_USER, DJ_PASS, DJ_STORES, โ€ฆ) and built-in defaults apply. No file under any parent directory of the working directory can contribute to config.

Configuration on Shared Hosts

On a machine that several people use, such as a lab server or a computing cluster, other users may be able to put files where DataJoint looks for its configuration. A configuration file placed by someone else could change where DataJoint connects or where it stores data.

Changed in 2.3.6

On Linux and macOS, DataJoint skips configuration files and secrets that another user could have placed. On Windows, there is no ownership check, and the search is unchanged.

What DataJoint Skips

The search for datajoint.json, for the .secrets/ directory and /run/secrets/datajoint/, and for the secret files in them skips an item when both of these are true:

  • It is owned by another user (not root).
  • It is in a directory that every user can write, such as /tmp, or below such a directory that lacks the sticky bit. The sticky bit, shown as the t in drwxrwxrwt on /tmp, stops users from removing or renaming each other's files.

Each skipped item is logged as a warning that names it, so DJ_LOG_LEVEL=ERROR hides it. The search does not continue to parent directories past a skipped datajoint.json.

A configuration file, secret file or secrets directory that is used and that every user can write also produces a warning. Restrict it with chmod o-w. A secrets directory that every user can write but that has the sticky bit, such as a root-owned /run/secrets/datajoint with mode 1777, produces no warning; each file in it is still checked.

These setups can be affected:

  • shared volumes with mode 0777 that another account fills, such as a Kubernetes emptyDir written by a helper container that runs as a different user;
  • container images whose files belong to a build user, are made writable by everyone with chmod -R 777, and run under a different user ID (for example on OpenShift);
  • Amazon EFS access-point roots with mode 0777, when the process runs as a different user;
  • NFS exports with root squashing (the server treats the client's root user as an unprivileged user);
  • WSL /mnt/c, when running as root or as another WSL user.

Use a Skipped File

If you trust a skipped file, do one of these:

  • set DJ_CONFIG_FILE to its path;
  • call dj.config.load(path);
  • change its owner with chown;
  • remove write permission for other users from the directory with chmod o-w.

Supply skipped secrets through environment variables.

Shared Group Directories

Files in a directory that only your group can write are still loaded, including one under a sticky /scratch. So every member of the group can change the configuration your sessions load. The search also continues up through parent directories, so a datajoint.json in a shared directory above your project is loaded when your project has none.

  • Keep a datajoint.json in each project, or set DJ_CONFIG_FILE. The search stops at the first datajoint.json it finds.
  • Let only people you trust write to group directories that hold DataJoint projects.
  • Do not run DataJoint from a directory that another user created, such as one under /tmp, unless you trust that user.
  • For services and shared pipelines, set DJ_IGNORE_CONFIG_FILE=true and supply every setting through environment variables. Setting environment variables alone is not enough, because they do not override every setting in a file (see Configuration Priority).

Security Best Practices

Development Environment

# 1. Initialize secrets directory
mkdir -p .secrets
chmod 700 .secrets  # Owner-only access

# 2. Create .gitignore
echo ".secrets/" >> .gitignore

# 3. Store credentials in .secrets/, one value per file
echo "dev_user"     > .secrets/database.user
echo "dev_password" > .secrets/database.password

# 4. Set restrictive permissions
chmod 600 .secrets/*

Production Environment

# Use environment variables from secure sources
export DJ_USER=$(vault read -field=username secret/datajoint/db)
export DJ_PASS=$(vault read -field=password secret/datajoint/db)

# Stores: one JSON-encoded env var (new in 2.2.4)
export DJ_STORES=$(vault read -format=json -field=stores secret/datajoint)

# Optional: guarantee no file on disk contributes to config (new in 2.2.3)
export DJ_IGNORE_CONFIG_FILE=true

CI/CD Environment

Use your CI system's secrets management:

GitHub Actions:

env:
  DJ_HOST: ${{ secrets.DJ_HOST }}
  DJ_USER: ${{ secrets.DJ_USER }}
  DJ_PASS: ${{ secrets.DJ_PASS }}

GitLab CI:

variables:
  DJ_HOST: $DJ_HOST
  DJ_USER: $DJ_USER
  DJ_PASS: $DJ_PASS

Docker Containers

Pass as environment variables:

docker run -e DJ_HOST=db.example.com \
           -e DJ_USER=myuser \
           -e DJ_PASS=mypassword \
           my-datajoint-app

Or mount secrets as read-only volume:

docker run -v $(pwd)/.secrets:/app/.secrets:ro \
           my-datajoint-app

Docker Compose:

services:
  app:
    image: my-datajoint-app
    env_file: .env
    volumes:
      - ./.secrets:/app/.secrets:ro

Cloud Platforms

AWS Lambda:

import os
import datajoint as dj

dj.config['database.user'] = os.environ['DJ_USER']
dj.config['database.password'] = os.environ['DJ_PASS']

Google Cloud Functions:

from google.cloud import secretmanager

client = secretmanager.SecretManagerServiceClient()
name = f"projects/{project_id}/secrets/dj-password/versions/latest"
response = client.access_secret_version(request={"name": name})
dj.config['database.password'] = response.payload.data.decode("UTF-8")

Azure Functions:

import os
import datajoint as dj

dj.config['database.user'] = os.environ['DJ_USER']
dj.config['database.password'] = os.environ['DJ_PASS']

Common Patterns

Local Development with Secrets Directory

import datajoint as dj

# Config loaded automatically from:
# 1. datajoint.json (project settings)
# 2. .secrets/database.user and .secrets/database.password (credentials)
conn = dj.conn()

Production with Environment Variables

import os
import datajoint as dj

# All configuration from environment
# No files needed
conn = dj.conn()

Multi-Environment Setup

Structure:

project/
โ”œโ”€โ”€ datajoint.json               # Shared settings
โ”œโ”€โ”€ .secrets/
โ”‚   โ”œโ”€โ”€ datajoint.dev.json      # Development credentials
โ”‚   โ”œโ”€โ”€ datajoint.staging.json  # Staging credentials
โ”‚   โ””โ”€โ”€ datajoint.prod.json     # Production credentials (if needed)
โ””โ”€โ”€ ...

Load by environment:

These per-environment JSON files are read by the snippet below, not by DataJoint's own secrets loader, so they can hold any settings and use any filenames. Assigning through dj.config[...] is a programmatic override, which outranks every other source.

import os
import datajoint as dj

env = os.getenv('ENV', 'dev')
secrets_path = f'.secrets/datajoint.{env}.json'

# Load environment-specific secrets
import json
with open(secrets_path) as f:
    secrets = json.load(f)
    for key, value in secrets.items():
        dj.config[key] = value

conn = dj.conn()

Troubleshooting

Secrets Not Loading

Check configuration priority:

import datajoint as dj

# View current configuration
print(dj.config)

# Check specific setting
print(dj.config['database.user'])

Find which files were picked up:

from datajoint.settings import find_config_file, find_secrets_dir

config_path = find_config_file()
print("config file:", config_path)
print("secrets dir:", find_secrets_dir(config_path))

If find_config_file() returns None, no datajoint.json was found via the upward search โ€” values come from environment variables and defaults only. From 2.3.6, it also returns None when the file found was skipped because another user could have placed it; the log then has a warning that names the file. See Configuration on Shared Hosts.

Permission Errors

# Fix .secrets/ permissions
chmod 700 .secrets
chmod 600 .secrets/*

Environment Variables Not Taking Effect

import os
import datajoint as dj

# Check environment variables are set
print(os.getenv('DJ_USER'))
print(os.getenv('DJ_PASS'))

# Force reload configuration
dj.config.clear()
conn = dj.conn(reset=True)

Accidentally Committed Secrets

Assume the secret is compromised

Once a credential reaches a remote branch, treat it as public. Anyone with repository access โ€” and any service that mirrors or caches commits โ€” may already have it. Rewriting git history does not un-leak the secret; rotation does.

Step 1 โ€” Rotate every exposed credential first. Do this before touching git history; until rotation completes, the leaked secret is still valid.

  • Database users (database.user / database.password): change the password on the server, then update your local .secrets/database.password.
  • Object-store credentials (stores.<name>.access_key / secret_key, or the equivalent in your cloud provider): issue new keys and revoke the old ones.
  • Any third-party tokens that appeared in the same file.
  • Audit recent access logs (DB connection log, S3 access log) for unfamiliar IPs or unexpected activity during the exposure window.

Step 2 โ€” Remove from git history. After rotation, scrub the file so old clones don't leak it further:

# Remove the leaked file from history (repeat per file, or pass several paths)
git filter-branch --force --index-filter \
  "git rm --cached --ignore-unmatch .secrets/database.password" \
  --prune-empty --tag-name-filter cat -- --all

# Force push (coordinate with team!)
git push origin --force --all

Step 3 โ€” Verify removal:

git log --all --full-history -- .secrets/database.password

Configuration Templates

Minimal Development Setup

// datajoint.json
{
  "database.host": "localhost",
  "safemode": true
}
// .secrets/ directory
.secrets/database.user                  # root
.secrets/database.password              # simple

Production with S3 Storage

// datajoint.json
{
  "database.host": "db.example.com",
  "database.port": 3306,
  "database.use_tls": true,
  "safemode": false,
  "stores": {
    "default": "main",
    "main": {
      "protocol": "s3",
      "endpoint": "s3.amazonaws.com",
      "bucket": "my-bucket",
      "location": "my-project"
    }
  }
}
// .secrets/ directory
.secrets/database.user                  # Database username
.secrets/database.password              # Database password
.secrets/stores.main.access_key         # S3 access key
.secrets/stores.main.secret_key         # S3 secret key

See Also