Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(dev): consolidate env vars, auto-resolve 1Password secrets (#45696)

Julian Bezf26fd80da01a
diff --git a/.env.development b/.env.development
new file mode 100644
index 000000000000..ed32d209cfa1
--- /dev/null
+++ b/.env.development
@@ -0,0 +1,75 @@
+# Development-mode runtime defaults (committed to repo).
+# Sourced by bin/start for host-side processes. Loaded into the sandbox
+# container via docker-compose env_file. Override in .env.local (gitignored).
+#
+# Service connection defaults (DATABASE_URL, REDIS_URL, KAFKA_HOSTS,
+# CLICKHOUSE_HOST, OBJECT_STORAGE_ENDPOINT, etc.) live in .env.services
+# — shared with hobby deployments via docker-compose env_file.
+
+# Core
+DEBUG=1
+SKIP_SERVICE_VERSION_REQUIREMENTS=1
+
+# Object storage (host-side only — container endpoint is in .env.services)
+# Browser-reachable host for presigned URLs (objectstorage:19000 only resolves inside Docker).
+OBJECT_STORAGE_PUBLIC_ENDPOINT=http://localhost:19000
+SESSION_RECORDING_V2_S3_ENDPOINT=http://localhost:8333
+
+# Redis host overrides (subsystems that don't read REDIS_URL)
+CDP_REDIS_HOST=redis7
+SESSION_RECORDING_API_REDIS_HOST=redis7
+COOKIELESS_REDIS_HOST=redis7
+
+# Temporal
+TEMPORAL_HOST=temporal
+
+# Services
+BILLING_SERVICE_URL=https://billing.dev.posthog.dev
+API_QUERIES_PER_TEAM={"1": 100}
+# Internal request token for Python <-> Rust service communication
+INTERNAL_REQUEST_TOKEN=dev-internal-token
+# Node.js ingestion consumer reaches Cymbal (Rust) on the host via lvh.me (cross-platform)
+ERROR_TRACKING_CYMBAL_BASE_URL=http://lvh.me:3302
+# Duckgres host port
+DUCKGRES_PORT=15432
+
+# Dagster
+DAGSTER_UI_HOST=localhost
+DAGSTER_UI_PORT=3030
+DAGSTER_WEB_PREAGGREGATED_MAX_PARTITIONS_PER_RUN=3000
+
+# OpenTelemetry
+OTEL_SERVICE_NAME=posthog-local-dev
+OTEL_PYTHON_LOG_LEVEL=debug
+# Collector's OTLP gRPC port is mapped to host
+OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
+OTEL_TRACES_EXPORTER=otlp
+# Explicitly disable if not used
+OTEL_METRICS_EXPORTER=none
+OTEL_LOGS_EXPORTER=none
+OTEL_PYTHON_DJANGO_INSTRUMENT=true
+OTEL_PYTHON_DJANGO_MIDDLEWARE_POSITION=1
+
+# DuckLake
+DUCKLAKE_RDS_HOST=localhost
+DUCKLAKE_RDS_PORT=5432
+DUCKLAKE_RDS_DATABASE=ducklake
+DUCKLAKE_RDS_USERNAME=posthog
+DUCKLAKE_RDS_PASSWORD=posthog
+DUCKLAKE_BUCKET=ducklake-dev
+DUCKLAKE_BUCKET_REGION=us-east-1
+DUCKLAKE_S3_ACCESS_KEY=object_storage_root_user
+DUCKLAKE_S3_SECRET_KEY=object_storage_root_password
+# Allow DuckLake catalog reset on version mismatch (dev convenience)
+POSTHOG_ALLOW_DUCKLAKE_CATALOG_RESET=1
+
+# Postgres schema fast-path restore mode for `hogli` (auto|off|...)
+POSTHOG_SCHEMA_RESTORE_IN_DEV=auto
+
+# personhog (Rust person/group service)
+PERSONHOG_ADDR=http://127.0.0.1:50052
+PERSONHOG_ENABLED=true
+PERSONHOG_ROLLOUT_PERCENTAGE=100
+
+# Debug
+PYDEVD_DISABLE_FILE_VALIDATION=1
diff --git a/.env.local.example b/.env.local.example
new file mode 100644
index 000000000000..39e67f4ced97
--- /dev/null
+++ b/.env.local.example
@@ -0,0 +1,23 @@
+# Personal dev overrides — copy to .env.local and uncomment what you need.
+# .env.local is gitignored, so put your secrets and personal preferences here.
+#
+# Any value using op:// auto-resolves via the 1Password CLI when bin/start
+# detects an op:// reference. Install with `brew install 1password-cli`.
+#
+# Precedence (highest wins): shell env > .env.local > .env.development > .env.services
+
+# ── AI features (PostHog employees) ───────────────────────────────────
+# Required to run Max and other AI features against real providers.
+# OPENAI_API_KEY=op://General/sbadkrbtbdgev4mjm4xtuirfoy/credential
+# ANTHROPIC_API_KEY=op://General/4n2rpvrjbmlkvpd464dekedzmy/credential
+# GOOGLE_API_KEY=op://General/53ir3ynk3e4h6ic4q4ftcph76i/credential
+# INKEEP_API_KEY=op://General/y5mqpg2xnmzosdqocob5phlgni/credential
+# AZURE_INFERENCE_ENDPOINT=op://General/yw6efvcz5ooxx5fgll3kyang5a/username
+# AZURE_INFERENCE_CREDENTIAL=op://General/yw6efvcz5ooxx5fgll3kyang5a/credential
+
+# ── Personal overrides ────────────────────────────────────────────────
+# Auto-login as a specific user (skips the login flow)
+
+# Use your own API keys instead of 1Password
+# OPENAI_API_KEY=sk-...
diff --git a/dev-services.env b/.env.services
similarity index 61%
rename from dev-services.env
rename to .env.services
index 3e92cef241ea..480432a92f08 100644
--- a/dev-services.env
+++ b/.env.services
@@ -1,12 +1,10 @@
+# Service connection defaults for local development and hobby deployments.
#
-# Shared service connection defaults for local development.
-# Referenced by docker-compose.base.yml (worker, web, migrate, etc.)
-# and docker-compose.sandbox.yml (app container).
-#
-# These override the localhost defaults in Django settings with Docker
-# service names, resolved via /etc/hosts on the host and Docker DNS
-# inside containers.
-#
+# Loaded into containers via docker-compose env_file (worker, sandbox, hobby
+# stack) AND into the host shell via bin/start. Hostnames (db, redis7, kafka,
+# clickhouse, objectstorage, temporal) resolve to 127.0.0.1 on the host via
+# /etc/hosts — see docs/published/handbook/engineering/developing-locally.md —
+# and via Docker DNS inside containers.
# Postgres
DATABASE_URL=postgres://posthog:posthog@db:5432/posthog
diff --git a/.github/workflows/ci-security.yaml b/.github/workflows/ci-security.yaml
index d0b69fd2a7cf..201db520ff51 100644
--- a/.github/workflows/ci-security.yaml
+++ b/.github/workflows/ci-security.yaml
@@ -56,7 +56,7 @@ jobs:
--error \
--metrics=off \
--verbose \
- common/ ee/ frontend/ posthog/ products/ services/llm-gateway/ services/stripe-mock/
+ bin/ common/ ee/ frontend/ posthog/ products/ services/llm-gateway/ services/stripe-mock/
semgrep-go:
runs-on: ubuntu-latest
@@ -218,7 +218,7 @@ jobs:
--severity=WARNING \
--metrics=off \
--verbose \
- common/ ee/ frontend/ posthog/ products/
+ bin/ common/ ee/ frontend/ posthog/ products/
# Pass 2: enforce ERROR-severity rules. Any finding fails the
# job — regression guards live here.
@@ -230,7 +230,7 @@ jobs:
--error \
--metrics=off \
--verbose \
- common/ ee/ frontend/ posthog/ products/
+ bin/ common/ ee/ frontend/ posthog/ products/
semgrep-test-rules:
runs-on: ubuntu-latest
diff --git a/.gitignore b/.gitignore
index 248400f6663c..9f15e454d979 100644
--- a/.gitignore
+++ b/.gitignore
@@ -182,16 +182,18 @@ QAREPORT.md
data/seaweedfs
data/seaweedfs/
-# No env files except for the example
+# No env files except for the example, development defaults, services, and local-overrides template
.env*
!.env.example
+!.env.development
+!.env.services
+!.env.local.example
# Ignore Agent OS (Claude Code) files
.claude/agents/agent-os
.claude/commands/agent-os
agent-os/
-
# MCP build files
services/mcp/public/ui-apps
diff --git a/.semgrep/devex-rules/env-default-belongs-in-env-development.yaml b/.semgrep/devex-rules/env-default-belongs-in-env-development.yaml
new file mode 100644
index 000000000000..aa7650270d1a
--- /dev/null
+++ b/.semgrep/devex-rules/env-default-belongs-in-env-development.yaml
@@ -0,0 +1,35 @@
+rules:
+ - id: env-default-belongs-in-env-development
+ message: |
+ Static bare-default `export VAR=${VAR:-default}` lines belong in
+ `.env.development` (sourced by `bin/start`), not in startup scripts.
+
+ Why: dev env defaults were historically scattered across `bin/start`,
+ `bin/start-backend`, and `bin/start-celery`. The cleanup puts a single
+ source of truth in `.env.development` (committed) with `.env.local`
+ (gitignored) for overrides + 1Password secrets. Only computed or
+ conditional logic should remain in startup scripts.
+
+ Move the default to `.env.development` and delete the export here.
+
+ Legitimate exceptions:
+ - Values that need bash variable expansion in their default
+ (`${PGHOST:-db}`, `$PERSONS_DATABASE_URL`) — the `.env.development`
+ loader doesn't re-expand $-refs. Suppress with
+ `# nosemgrep: env-default-belongs-in-env-development -- bash variable ref`
+ on the line above.
+ - Computed/platform-conditional values (e.g., guarded by `uname`
+ checks, derived from `$REPOSITORY_ROOT`) — these don't match this
+ rule's regex anyway.
+ languages: [generic]
+ severity: ERROR
+ paths:
+ include:
+ - '/bin/start'
+ - '/bin/start-backend'
+ - '/bin/start-celery'
+ pattern-regex: '(?m)^\s*export\s+[A-Z_][A-Z0-9_]*=\$\{[A-Z_][A-Z0-9_]*:-[^}]+\}\s*$'
+ metadata:
+ category: best-practice
+ subcategory:
+ - audit
diff --git a/bin/deploy-hobby b/bin/deploy-hobby
index 25307ce64179..36384ef4bbeb 100755
--- a/bin/deploy-hobby
+++ b/bin/deploy-hobby
@@ -224,7 +224,7 @@ echo "Configuring Docker Compose...."
rm -f docker-compose.yml
cp posthog/docker-compose.base.yml docker-compose.base.yml
cp posthog/docker-compose.hobby.yml docker-compose.yml
-cp posthog/dev-services.env dev-services.env
+cp posthog/.env.services .env.services
echo "Starting the stack!"
# Retry docker-compose up with --pull always up to 3 times
for attempt in 1 2 3; do
diff --git a/bin/hobby-installer/core/git.go b/bin/hobby-installer/core/git.go
index ea1c850006bf..f8e660d001c9 100644
--- a/bin/hobby-installer/core/git.go
+++ b/bin/hobby-installer/core/git.go
@@ -151,9 +151,9 @@ func CopyComposeFiles() error {
return err
}
- // Copy the shared env file that docker-compose.base.yml references via env_file.
- if err := copyFile("posthog/dev-services.env", "dev-services.env"); err != nil {
- logger.Debug("Failed to copy dev-services.env: %v", err)
+ // Copy the shared service-connection env file that docker-compose.base.yml references via env_file.
+ if err := copyFile("posthog/.env.services", ".env.services"); err != nil {
+ logger.Debug("Failed to copy .env.services: %v", err)
return err
}
diff --git a/bin/start b/bin/start
index 8f9226e99d54..0434e873e2dc 100755
--- a/bin/start
+++ b/bin/start
@@ -19,10 +19,46 @@ fi
trap cleanup_lock EXIT INT TERM
-export SESSION_RECORDING_V2_S3_ENDPOINT=${SESSION_RECORDING_V2_S3_ENDPOINT:-http://seaweedfs:8333}
+# 1Password: auto-resolve op:// references in .env.local
+if [ -f "$REPOSITORY_ROOT/.env.local" ] && grep -q "op://" "$REPOSITORY_ROOT/.env.local" 2>/dev/null; then
+ if [ -z "$_POSTHOG_OP_RESOLVED" ]; then
+ if command -v op &>/dev/null; then
+ echo "🔐 Resolving secrets from .env.local via 1Password"
+ export _POSTHOG_OP_RESOLVED=1
+ exec op run --env-file="$REPOSITORY_ROOT/.env.local" -- "$0" "$@"
+ else
+ echo "⚠️ .env.local contains 1Password refs (op://) but 'op' CLI not found"
+ echo " Install: brew install 1password-cli"
+ fi
+ fi
+fi
-export DEBUG=${DEBUG:-1}
-export SKIP_SERVICE_VERSION_REQUIREMENTS=${SKIP_SERVICE_VERSION_REQUIREMENTS:-1}
+# Environment variables are defined in:
+# .env.services - service connection defaults (shared with containers
+# and hobby via docker-compose env_file)
+# .env.development - dev-mode runtime knobs (DEBUG, OTEL, etc.)
+# .env.local - your overrides + 1Password secrets (gitignored,
+# copy .env.local.example to get started)
+#
+# Source env files respecting precedence:
+# shell env > .env.local > .env.development > .env.services
+# Only set vars that aren't already in the environment
+source_env_defaults() {
+ while IFS='=' read -r name value; do
+ [[ -z "$name" || "$name" == \#* ]] && continue
+ [[ -z "${!name:-}" ]] && export "$name=$value"
+ done < "$1"
+}
+# .env.local: already in env if processed by op run, otherwise source directly
+if [[ -f "$REPOSITORY_ROOT/.env.local" ]] && [[ -z "$_POSTHOG_OP_RESOLVED" ]]; then
+ source_env_defaults "$REPOSITORY_ROOT/.env.local"
+fi
+source_env_defaults "$REPOSITORY_ROOT/.env.development"
+source_env_defaults "$REPOSITORY_ROOT/.env.services"
+
+# Limit Rust parallel compilation jobs to reduce CPU contention when multiple
+# services start simultaneously via mprocs (they share a build lock anyway)
+export CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-1}"
# Use sccache for Rust compilation caching (if available via flox or homebrew)
if [[ -z "${RUSTC_WRAPPER:-}" ]] && command -v sccache &>/dev/null; then
@@ -34,27 +70,8 @@ if [[ "$(uname -s)" == "Darwin" ]] && [[ -z "${CARGO_TARGET_AARCH64_APPLE_DARWIN
export CARGO_TARGET_AARCH64_APPLE_DARWIN_RUSTFLAGS="-C link-arg=-fuse-ld=lld"
fi
-export BILLING_SERVICE_URL=${BILLING_SERVICE_URL:-https://billing.dev.posthog.dev}
-export API_QUERIES_PER_TEAM='{"1": 100}'
-
-# Internal request token for Python <-> Rust service communication
-export INTERNAL_REQUEST_TOKEN=${INTERNAL_REQUEST_TOKEN:-dev-internal-token}
-
-# Dagster
+# Computed vars (need REPOSITORY_ROOT)
export DAGSTER_HOME=$REPOSITORY_ROOT/.dagster_home
-export DAGSTER_UI_HOST=${DAGSTER_UI_HOST:-localhost}
-export DAGSTER_UI_PORT=${DAGSTER_UI_PORT:-3030}
-export DAGSTER_WEB_PREAGGREGATED_MAX_PARTITIONS_PER_RUN=${DAGSTER_WEB_PREAGGREGATED_MAX_PARTITIONS_PER_RUN:-3000}
-
-# OpenTelemetry Environment Variables
-export OTEL_SERVICE_NAME="posthog-local-dev"
-export OTEL_PYTHON_LOG_LEVEL="debug"
-export OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4317" # Collector's OTLP gRPC port is mapped to host
-export OTEL_TRACES_EXPORTER="otlp"
-export OTEL_METRICS_EXPORTER="none" # Explicitly disable if not used
-export OTEL_LOGS_EXPORTER="none" # Explicitly disable if not used
-export OTEL_PYTHON_DJANGO_INSTRUMENT="true"
-export OTEL_PYTHON_DJANGO_MIDDLEWARE_POSITION="1"
# Tracing is disabled by default - requires 'tracing' intent for Jaeger/otel-collector
# Note: otel-collector uses significant CPU/memory resources
@@ -68,47 +85,22 @@ else
export OTEL_SDK_DISABLED="true"
fi
-if [ -f .env ]; then
- set -o allexport
- source .env
- set +o allexport
-fi
+# Vars below need bash variable expansion in their defaults (${PGHOST:-db},
+# $PERSONS_DATABASE_URL, etc.) — must stay in this script because
+# .env.development is sourced via a loader that doesn't re-expand $-refs.
-export POSTHOG_SCHEMA_RESTORE_IN_DEV=${POSTHOG_SCHEMA_RESTORE_IN_DEV:-auto}
-
-# Ducklake
-export DUCKLAKE_RDS_HOST=${DUCKLAKE_RDS_HOST:-db}
-export DUCKLAKE_RDS_PORT=${DUCKLAKE_RDS_PORT:-5432}
-export DUCKLAKE_RDS_DATABASE=${DUCKLAKE_RDS_DATABASE:-ducklake}
-export DUCKLAKE_RDS_USERNAME=${DUCKLAKE_RDS_USERNAME:-posthog}
-export DUCKLAKE_RDS_PASSWORD=${DUCKLAKE_RDS_PASSWORD:-posthog}
-export DUCKLAKE_BUCKET=${DUCKLAKE_BUCKET:-ducklake-dev}
-export DUCKLAKE_BUCKET_REGION=${DUCKLAKE_BUCKET_REGION:-us-east-1}
-export DUCKLAKE_S3_ACCESS_KEY=${DUCKLAKE_S3_ACCESS_KEY:-object_storage_root_user}
-export DUCKLAKE_S3_SECRET_KEY=${DUCKLAKE_S3_SECRET_KEY:-object_storage_root_password}
-export POSTHOG_ALLOW_DUCKLAKE_CATALOG_RESET=${POSTHOG_ALLOW_DUCKLAKE_CATALOG_RESET:-1}
-
-# These default to localhost/127.0.0.1 in Node.js/Rust configs
-export CDP_REDIS_HOST=${CDP_REDIS_HOST:-redis7}
-export SESSION_RECORDING_API_REDIS_HOST=${SESSION_RECORDING_API_REDIS_HOST:-redis7}
-export COOKIELESS_REDIS_HOST=${COOKIELESS_REDIS_HOST:-redis7}
-export TEMPORAL_HOST=${TEMPORAL_HOST:-temporal}
# Persons DB — Node.js and Rust use different env var names for the same connection
export PERSONS_DATABASE_URL=${PERSONS_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/posthog_persons}
export PERSONS_READONLY_DATABASE_URL=${PERSONS_READONLY_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/posthog_persons}
+# nosemgrep: env-default-belongs-in-env-development -- bash variable ref in default
export PERSONS_WRITE_DATABASE_URL=${PERSONS_WRITE_DATABASE_URL:-$PERSONS_DATABASE_URL}
+# nosemgrep: env-default-belongs-in-env-development -- bash variable ref in default
export PERSONS_READ_DATABASE_URL=${PERSONS_READ_DATABASE_URL:-$PERSONS_READONLY_DATABASE_URL}
-# Error tracking — Node.js ingestion consumer needs to reach Cymbal (Rust) on the host
-# Using lvh.me instead of localhost for cross-platform compatibility
-export ERROR_TRACKING_CYMBAL_BASE_URL=${ERROR_TRACKING_CYMBAL_BASE_URL:-http://lvh.me:3302}
export BEHAVIORAL_COHORTS_DATABASE_URL=${BEHAVIORAL_COHORTS_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/behavioral_cohorts}
export FLAGS_READ_STORE_DATABASE_URL=${FLAGS_READ_STORE_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/flags_read_store}
export CYCLOTRON_DATABASE_URL=${CYCLOTRON_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/cyclotron}
export CYCLOTRON_NODE_DATABASE_URL=${CYCLOTRON_NODE_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/cyclotron_node}
-# Duckgres
-export DUCKGRES_PORT=${DUCKGRES_PORT:-15432}
-
# Geo files
./bin/download-mmdb
diff --git a/bin/start-backend b/bin/start-backend
index f7ab2c6b776a..859bef711b05 100755
--- a/bin/start-backend
+++ b/bin/start-backend
@@ -1,25 +1,10 @@
#!/bin/bash
set -e
+# Computed vars (need a fresh tempdir per invocation) — must stay in script
export PROMETHEUS_MULTIPROC_DIR=$(mktemp -d)
trap 'rm -rf "$PROMETHEUS_MULTIPROC_DIR"' EXIT
-export OBJECT_STORAGE_ENDPOINT=${OBJECT_STORAGE_ENDPOINT:-http://objectstorage:19000}
-# Browser-reachable host for presigned URLs (objectstorage:19000 only resolves inside Docker).
-export OBJECT_STORAGE_PUBLIC_ENDPOINT=${OBJECT_STORAGE_PUBLIC_ENDPOINT:-http://localhost:19000}
-export SESSION_RECORDING_V2_S3_ENDPOINT=${SESSION_RECORDING_V2_S3_ENDPOINT:-http://localhost:8333}
-
-export CLICKHOUSE_API_USER="api"
-export CLICKHOUSE_API_PASSWORD="apipass"
-export CLICKHOUSE_APP_USER="app"
-export CLICKHOUSE_APP_PASSWORD="apppass"
-
-export PERSONHOG_ADDR=${PERSONHOG_ADDR:-http://127.0.0.1:50052}
-export PERSONHOG_ENABLED=${PERSONHOG_ENABLED:-true}
-export PERSONHOG_ROLLOUT_PERCENTAGE=${PERSONHOG_ROLLOUT_PERCENTAGE:-100}
-
-# Suppress frozen modules warning since we only debug our code, not stdlib
-export PYDEVD_DISABLE_FILE_VALIDATION=1
# Cross-platform Docker host access
# On macOS/Windows: Docker runs in a VM, use 127.0.0.1 for the host bind
diff --git a/bin/start-celery b/bin/start-celery
index ad5c082e6f93..ffefe0298e29 100755
--- a/bin/start-celery
+++ b/bin/start-celery
@@ -3,11 +3,6 @@
set -e
-export CLICKHOUSE_API_USER="api"
-export CLICKHOUSE_API_PASSWORD="apipass"
-export CLICKHOUSE_APP_USER="app"
-export CLICKHOUSE_APP_PASSWORD="apppass"
-
source ./bin/celery-queues.env
# start celery worker with heartbeat (-B)
diff --git a/bin/upgrade-hobby b/bin/upgrade-hobby
index 97b931616470..ef92b84257b1 100755
--- a/bin/upgrade-hobby
+++ b/bin/upgrade-hobby
@@ -298,7 +298,7 @@ sudo chmod +x /usr/local/bin/docker-compose
rm -f docker-compose.yml
cp posthog/docker-compose.base.yml docker-compose.base.yml
cp posthog/docker-compose.hobby.yml docker-compose.yml.tmpl
-cp posthog/dev-services.env dev-services.env
+cp posthog/.env.services .env.services
envsubst < docker-compose.yml.tmpl > docker-compose.yml
rm docker-compose.yml.tmpl
diff --git a/docker-compose.base.yml b/docker-compose.base.yml
index 358d63d625b0..aae943e7f006 100644
--- a/docker-compose.base.yml
+++ b/docker-compose.base.yml
@@ -265,7 +265,7 @@ services:
worker: &worker
command: ./bin/docker-worker-celery --with-scheduler
restart: on-failure
- env_file: dev-services.env
+ env_file: .env.services
environment: &worker_env
OTEL_SDK_DISABLED: 'true'
API_QUERIES_PER_TEAM: '{"1": 100}'
diff --git a/docker-compose.sandbox.yml b/docker-compose.sandbox.yml
index 792b9c006d93..cd5635156a1b 100644
--- a/docker-compose.sandbox.yml
+++ b/docker-compose.sandbox.yml
@@ -166,9 +166,11 @@ services:
- python-env:/cache/python
# JetBrains IDE backend for Gateway (populated by bin/sandbox)
- jetbrains:/opt/idea
- # Shared service defaults (Postgres, ClickHouse, Redis, etc.) come from
- # the same env file used by docker-compose.base.yml.
- env_file: dev-services.env
+ # Sandbox uses the shared service-connection defaults but NOT .env.development —
+ # the latter has host-side URLs (SESSION_RECORDING_V2_S3_ENDPOINT=localhost:8333,
+ # OBJECT_STORAGE_PUBLIC_ENDPOINT=localhost:19000) that don't resolve inside the
+ # container. Dev runtime knobs (DEBUG, etc.) are set inline below.
+ env_file: .env.services
environment:
# --- Sandbox identity ---
SANDBOX_UID: '${SANDBOX_UID:-1000}'
diff --git a/docs/published/handbook/engineering/developing-locally.md b/docs/published/handbook/engineering/developing-locally.md
index 00fdcf8a5c2f..9cd0c33cc021 100644
--- a/docs/published/handbook/engineering/developing-locally.md
+++ b/docs/published/handbook/engineering/developing-locally.md
@@ -150,6 +150,26 @@ You can now change PostHog in any way you want. See [Project structure](./projec
By default, `hogli start` runs a minimal set of services (enough for product analytics). To customize which services start, run `hogli dev:setup` which lets you select intents based on the products you're working on. Your choices are saved and used automatically by `hogli start`.
+### Setting environment variables
+
+Three env files come into play when `hogli start` runs:
+
+- `.env.services` (committed) — how to reach local services like Postgres, Redis, Kafka, ClickHouse. Shared with hobby deployments and Docker containers.
+- `.env.development` (committed) — dev-mode runtime knobs: `DEBUG`, OpenTelemetry, DuckLake, ports, etc.
+- `.env.local` (gitignored) — your overrides and secrets. Copy `.env.local.example` to get started.
+
+Precedence (highest wins): `shell env > .env.local > .env.development > .env.services`.
+
+To run AI features locally, you'll need API keys for OpenAI, Anthropic, and others. PostHog employees can pull them from 1Password without ever pasting raw values:
+
+```bash
+cp .env.local.example .env.local # uncomment the op:// lines you need
+brew install 1password-cli # one-time
+hogli start # auto-resolves op:// via `op run`
+```
+
+If `bin/start` sees any `op://` reference in `.env.local`, it re-execs itself under `op run --env-file=.env.local`. No need to remember the wrapper command.
+
### Running in detached mode
By default, `hogli start` runs interactively with a terminal UI (phrocs) that displays logs from all processes. If you prefer to run the dev stack in the background without an attached terminal, use detached mode:
diff --git a/tools/hogli/src/hogli/cli.py b/tools/hogli/src/hogli/cli.py
index 04d6259b6ecb..71b990a415f0 100644
--- a/tools/hogli/src/hogli/cli.py
+++ b/tools/hogli/src/hogli/cli.py
@@ -254,6 +254,62 @@ def concepts() -> None:
click.echo()
+def _load_env_file(path: os.PathLike[str], only_if_unset: bool = True) -> None:
+ """Load environment variables from a file (KEY=VALUE per line, # comments)."""
+ from pathlib import Path
+
+ env_file = Path(path)
+ if not env_file.exists():
+ return
+
+ for line in env_file.read_text().splitlines():
+ line = line.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ name, _, value = line.partition("=")
+ if only_if_unset and name in os.environ:
+ continue
+ os.environ[name] = value
+
+
[email protected](name="run", help="Run a command with resolved environment (1Password + defaults)")
[email protected]("command", nargs=-1, required=True)
+def run_with_env(command: tuple[str, ...]) -> None:
+ """Run a command with PostHog environment variables.
+
+ Loads .env.development defaults and .env.local overrides.
+ If .env.local contains 1Password references (op://), resolves them via `op run`.
+
+ Note: When using 1Password, op run's .env.local takes precedence over shell env.
+ This is op's design — secrets from 1Password are meant to win.
+
+ Examples:
+ hogli run ./manage.py shell
+ hogli run pytest posthog/api/
+ """
+ env_dev = REPO_ROOT / ".env.development"
+ env_services = REPO_ROOT / ".env.services"
+ env_local = REPO_ROOT / ".env.local"
+
+ has_op_refs = env_local.exists() and "op://" in env_local.read_text()
+
+ if has_op_refs:
+ if not shutil.which("op"):
+ click.echo("⚠️ .env.local contains 1Password refs (op://) but 'op' CLI not found", err=True)
+ click.echo(" Install: brew install 1password-cli", err=True)
+ raise SystemExit(1)
+ # Load .env.development and .env.services first (only if not already set in shell).
+ # op run then layers .env.local on top — overriding our files but not shell.
+ _load_env_file(env_dev, only_if_unset=True)
+ _load_env_file(env_services, only_if_unset=True)
+ os.execvp("op", ["op", "run", f"--env-file={env_local}", "--", *command])
+ else:
+ _load_env_file(env_local, only_if_unset=True)
+ _load_env_file(env_dev, only_if_unset=True)
+ _load_env_file(env_services, only_if_unset=True)
+ os.execvp(command[0], list(command))
+
+
def _register_script_commands() -> None:
"""Dynamically register commands from hogli.yaml.