ZORL

zorath-env Documentation

Package: zorath-env | Binary: zenv

Everything you need to get started with zorath-env.

1. Installation

Install zorath-env using Cargo (Rust package manager). The package installs as the zenv binary:

From crates.io

cargo install zorath-env

From source

git clone https://github.com/zorl-engine/zorath-env.git
cd zorath-env
cargo install --path .

After installation, verify it works by running:

zenv version

2. Quick Start

Option A: Start from scratch

Create an env.schema.json file in your project root:

{
  "DATABASE_URL": {
    "type": "url",
    "required": true,
    "description": "Database connection string"
  },
  "PORT": {
    "type": "int",
    "required": false,
    "default": 3000,
    "description": "Server port number"
  }
}

Option B: Generate from existing .env.example

If you already have a .env.example file, generate a schema from it:

zenv init

This creates an env.schema.json with intelligent type inference (detects bool, int, float, url). Edit the file to add descriptions and refine types.

Validate your .env

Once you have both .env and env.schema.json, run:

$ zenv check

zenv: OK

3. Schema Reference

Schema Structure

The schema file is a JSON object where each key is a variable name:

{
  "VARIABLE_NAME": {
    "type": "string",
    "required": true,
    "default": "value",
    "description": "What this variable does",
    "values": ["option1", "option2"],
    "validate": { "min_length": 1 }
  }
}

Variable Properties

PropertyTypeRequiredDescription
typestringYesThe data type of the variable
requiredbooleanNoWhether the variable must be present (default: false)
defaultstringNoDefault value if not provided
descriptionstringNoHuman-readable description
valuesstring[]For enumList of allowed values (required for enum type)
validateobjectNoValidation rules (min/max, min_length/max_length, pattern)

Supported Types

string

Any string value. This is the default type.

"API_KEY": { "type": "string", "required": true }
int

Integer numbers only. Validates that the value can be parsed as an integer.

"PORT": { "type": "int", "default": "3000" }
float

Floating-point numbers. Validates that the value can be parsed as a float.

"RATE_LIMIT": { "type": "float", "default": "1.5" }
bool

Boolean values. Accepts true, false, 1, 0, yes, no (case-insensitive).

"DEBUG": { "type": "bool", "default": false }
url

Valid URL format. Validates URL structure.

"DATABASE_URL": { "type": "url", "required": true }
enum

One of the specified values. Requires the values property.

"LOG_LEVEL": { "type": "enum", "values": ["debug", "info", "warn", "error"] }
uuid

UUID version 4 format (xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx).

"SESSION_ID": { "type": "uuid", "required": true }
email

Valid email address format with basic RFC 5322 validation.

"ADMIN_EMAIL": { "type": "email", "required": true }
ipv4

Valid IPv4 address in dotted decimal notation (0.0.0.0 to 255.255.255.255).

"SERVER_IP": { "type": "ipv4", "default": "127.0.0.1" }
ipv6

Valid IPv6 address in standard notation.

"IPV6_ADDR": { "type": "ipv6", "required": false }
semver

Semantic version format (MAJOR.MINOR.PATCH with optional prerelease/build metadata).

"APP_VERSION": { "type": "semver", "default": "1.0.0" }
port

Valid network port number between 1 and 65535.

"HTTP_PORT": { "type": "port", "default": "8080" }
date

ISO 8601 date format (YYYY-MM-DD).

"RELEASE_DATE": { "type": "date", "required": false }
hostname

Valid hostname or domain name per RFC 1123.

"API_HOST": { "type": "hostname", "default": "localhost" }

4. CLI Commands

zenv check

Validates your .env file against the schema. Optionally scan for leaked secrets. Returns exit code 0 on success, 1 on failure.

Options:

  • --env <path> - Path to .env file (default: .env)
  • --schema <path> - Path to schema file (default: env.schema.json)
  • --allow-missing-env - Allow missing .env if schema validates (default: true)
  • --detect-secrets - Scan for potential secrets (AWS keys, tokens, passwords)
  • --watch - Watch mode for continuous validation with delta detection
  • --format <format> - Output format: text or json (default: text)
  • --no-cache - Bypass schema cache for remote URLs
  • --verify-hash <hash> - Verify remote schema SHA-256 hash
  • --ca-cert <path> - Custom CA certificate (PEM format)

Example:

$ zenv check
zenv: OK

$ zenv check --format json
{"valid":true,"errors":[],"warnings":[]}

$ zenv check --watch
[14:32:15] Watching .env and env.schema.json...
[14:32:20] Change detected in .env
zenv: OK

zenv diff

Compare two .env files and show differences. Find variables only in one file, or with different values.

Options:

  • <file_a> - First .env file
  • <file_b> - Second .env file
  • --schema <path> - Also check schema compliance for both files
  • --format <format> - Output format: text or json (default: text)
  • --no-cache - Bypass schema cache for remote URLs
  • --verify-hash <hash> - Verify remote schema SHA-256 hash
  • --ca-cert <path> - Custom CA certificate (PEM format)

Example:

$ zenv diff .env.development .env.production

Only in .env.development:
- DEBUG_MODE

Different values:
- NODE_ENV: "development" vs "production"

$ zenv diff .env.dev .env.prod --format json

zenv init

Generates a schema file from an existing .env.example file with intelligent type inference and smart description generation based on key names.

Options:

  • --example <path> - Path to .env.example (default: .env.example)
  • --schema <path> - Output path (default: env.schema.json)

Example:

$ zenv init
Created env.schema.json from .env.example

zenv docs

Generates documentation from your schema. Outputs to stdout.

Options:

  • --schema <path> - Path to schema file (default: env.schema.json)
  • --format <format> - Output format: markdown or json (default: markdown)
  • --no-cache - Bypass schema cache for remote URLs
  • --verify-hash <hash> - Verify remote schema SHA-256 hash
  • --ca-cert <path> - Custom CA certificate (PEM format)

Example:

$ zenv docs
# prints markdown to stdout

$ zenv docs --format json > schema.json

zenv example

Generate .env.example from schema (reverse of init).

Options:

  • --schema <path> - Path to schema (default: env.schema.json)
  • --output <path> - Output file (default: stdout)
  • --include-defaults - Include default values in output
  • --no-cache - Bypass schema cache for remote URLs
  • --verify-hash <hash> - Verify remote schema SHA-256 hash
  • --ca-cert <path> - Custom CA certificate (PEM format)

Example:

$ zenv example
# outputs to stdout

$ zenv example --include-defaults --output .env.example

zenv version

Displays the current version of zenv with optional update check and changelog links.

Options:

  • --check-update - Check crates.io for newer version

Example:

$ zenv version
zenv v0.3.8

$ zenv version --check-update
zenv v0.3.8
You are on the latest version.

zenv completions

Generate shell completions for bash, zsh, fish, or PowerShell.

Options:

  • <SHELL> - Shell type: bash, zsh, fish, powershell

Example:

$ zenv completions bash > ~/.bash_completion.d/zenv
$ zenv completions zsh > ~/.zfunc/_zenv
$ eval "$(zenv completions bash)"

zenv export

Export .env files to various deployment formats. Supports 7 output formats for different platforms.

Options:

  • <env_file> - Path to .env file to export
  • --format <format> - Output format: shell, docker, k8s, json, systemd, dotenv, github-secrets
  • --schema <path> - Filter to only schema-defined variables
  • --output <path> - Write to file instead of stdout
  • --no-cache - Bypass schema cache for remote URLs
  • --verify-hash <hash> - Verify remote schema SHA-256 hash
  • --ca-cert <path> - Custom CA certificate (PEM format)

Example:

$ zenv export .env --format shell
export DATABASE_URL="postgres://..."

$ zenv export .env --format docker
ENV DATABASE_URL=postgres://...

$ zenv export .env --format k8s
apiVersion: v1
kind: ConfigMap
data:
  DATABASE_URL: postgres://...

zenv doctor

Run comprehensive health diagnostics. Checks installation, schemas, env files, cache, and shell completions.

Example:

$ zenv doctor
zenv Doctor
===========

Installation
  Version: 0.3.8
  Binary: /usr/local/bin/zenv

Schema Files
  env.schema.json: found

Environment Files
  .env: found
  .env.local: found

Cache
  Path: ~/.cache/zorath-env
  Entries: 3

Shell Completions
  bash: not installed
  zsh: installed

zenv fix

Automatically fix common .env issues. Creates a backup before making changes.

Options:

  • --env <path> - Path to .env file (default: .env)
  • --schema <path> - Path to schema file (default: env.schema.json)
  • --sort - Sort variables alphabetically
  • --add-missing - Add missing required variables with defaults
  • --remove-unknown - Remove variables not in schema
  • --dry-run - Show changes without applying
  • --no-backup - Skip creating backup file
  • --no-cache - Bypass schema cache for remote URLs
  • --verify-hash <hash> - Verify remote schema SHA-256 hash
  • --ca-cert <path> - Custom CA certificate (PEM format)

Example:

$ zenv fix --dry-run
Would make the following changes:
  + Add: LOG_LEVEL=info (default)
  - Remove: DEPRECATED_VAR
  ~ Sort: 15 variables

$ zenv fix
Backup created: .env.backup
Fixed 3 issues in .env

zenv scan

Scan source code for environment variable usage. Finds unused schema variables and undeclared env references.

Options:

  • --path <dir> - Directory to scan (default: .)
  • --schema <path> - Path to schema file (default: env.schema.json)
  • --format <format> - Output format: text or json (default: text)
  • --show-unused - Show variables in schema but not in code
  • --no-cache - Bypass schema cache for remote URLs
  • --verify-hash <hash> - Verify remote schema SHA-256 hash
  • --ca-cert <path> - Custom CA certificate (PEM format)

Example:

$ zenv scan --show-unused
Scanning 142 files...

Unused (in schema but not in code):
  - OLD_API_KEY
  - LEGACY_MODE

Used variables: 23
Files scanned: 142
Languages: JavaScript, TypeScript, Python

zenv cache

Manage the remote schema cache. View cache location, list entries, clear cached schemas, or view statistics.

Options:

  • path - Show cache directory path
  • list - List all cached schemas with URLs and ages
  • clear [url] - Clear all cache or specific URL
  • stats - Show cache health statistics and size

Example:

$ zenv cache path
~/.cache/zorath-env

$ zenv cache list
Cached schemas:
  1. https://example.com/schema.json (2h ago)
  2. https://team.dev/env.schema.json (15m ago)

$ zenv cache stats
Cache Statistics:
  Total entries: 2
  Total size: 4.2 KB
  Oldest: 2h ago

$ zenv cache clear
Cleared 2 cached schemas

zenv template

Generate CI/CD configuration templates for environment validation. Supports GitHub Actions, GitLab CI, and CircleCI.

Options:

  • <template> - Template name: github (gh), gitlab (gl), circleci (circle)
  • --output <path> - Write to file instead of stdout
  • --list - List available templates

Example:

$ zenv template --list
Available templates:
  github   - GitHub Actions workflow
  gitlab   - GitLab CI pipeline
  circleci - CircleCI config

$ zenv template github
# Outputs GitHub Actions YAML to stdout

$ zenv template github --output .github/workflows/env-validation.yml
Created .github/workflows/env-validation.yml

zenv --help

Shows help information and available commands.

Example:

$ zenv --help

5. Examples

Web Application

{
  "NODE_ENV": {
    "type": "enum",
    "values": ["development", "production", "test"],
    "required": true,
    "description": "Application environment"
  },
  "PORT": {
    "type": "int",
    "required": false,
    "default": 3000,
    "description": "HTTP server port",
    "validate": { "min": 1024, "max": 65535 }
  },
  "DATABASE_URL": {
    "type": "url",
    "required": true,
    "description": "PostgreSQL connection string"
  },
  "JWT_SECRET": {
    "type": "string",
    "required": true,
    "description": "Secret key for JWT signing",
    "validate": { "min_length": 32, "max_length": 128 }
  },
  "DEBUG": {
    "type": "bool",
    "required": false,
    "default": false,
    "description": "Enable debug logging"
  }
}

API Service

{
  "API_HOST": {
    "type": "string",
    "required": false,
    "default": "0.0.0.0",
    "description": "Host to bind the API server"
  },
  "API_PORT": {
    "type": "int",
    "required": false,
    "default": 8080,
    "description": "Port for the API server",
    "validate": { "min": 1, "max": 65535 }
  },
  "LOG_LEVEL": {
    "type": "enum",
    "values": ["debug", "info", "warn", "error"],
    "required": false,
    "default": "info",
    "description": "Logging verbosity level"
  },
  "RATE_LIMIT": {
    "type": "float",
    "required": false,
    "default": 100.0,
    "description": "Requests per second limit",
    "validate": { "min_value": 0.0, "max_value": 10000.0 }
  },
  "CORS_ORIGIN": {
    "type": "url",
    "required": false,
    "description": "Allowed CORS origin"
  }
}

6. .env File Features

zenv supports advanced .env file features beyond simple key=value pairs.

Variable Interpolation

Reference other variables using ${VAR} or $VAR syntax:

BASE_URL=https://api.example.com
API_ENDPOINT=${BASE_URL}/v2
PORT=3000
SERVER_URL=http://localhost:${PORT}

Circular references are detected and will cause a validation error.

Multiline Values

Double-quoted strings can span multiple lines:

SSH_KEY="-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA...
-----END RSA PRIVATE KEY-----"

Escape Sequences

Double-quoted strings support escape sequences:

SequenceResult
\nNewline
\tTab
\rCarriage return
\\Backslash
\"Double quote

Comments and Export Syntax

Full-line comments, inline comments, shell export syntax, and blank lines are supported:

# This is a full-line comment
DATABASE_URL=postgres://localhost/db  # inline comment

# Shell export syntax works too
export NODE_ENV=production
export DEBUG=false

.env Fallback Chain

If .env is not found, zenv automatically checks these fallbacks in order:

  • .env.local
  • .env.development
  • .env.development.local

7. Schema Inheritance

Extend base schemas for environment-specific configurations using the extends field.

Base Schema (base.schema.json)

{
  "DATABASE_URL": {
    "type": "url",
    "required": true,
    "description": "Database connection string"
  },
  "LOG_LEVEL": {
    "type": "enum",
    "values": ["debug", "info", "warn", "error"],
    "default": "info"
  }
}

Production Schema (prod.schema.json)

{
  "extends": "base.schema.json",
  "SENTRY_DSN": {
    "type": "url",
    "required": true,
    "description": "Sentry error tracking DSN"
  },
  "LOG_LEVEL": {
    "type": "enum",
    "values": ["info", "warn", "error"],
    "default": "warn"
  }
}

The production schema inherits all variables from base.schema.json, adds SENTRY_DSN, and overrides LOG_LEVEL to exclude debug level.

Inheritance supports up to 10 levels of depth. Circular references are detected and will cause an error.

8. CI/CD Integration

zenv is designed for CI/CD pipelines with clear exit codes and easy integration.

Exit Codes

CodeMeaning
0Validation passed
1Validation failed
2File error (missing .env or cannot read)
3Schema error (invalid or missing schema)

Pre-commit Hook

Add to .git/hooks/pre-commit or use with pre-commit framework:

#!/usr/bin/env bash
set -e

if [ -f "env.schema.json" ]; then
  if command -v zenv >/dev/null 2>&1; then
    zenv check || exit 1
  else
    echo "Warning: zenv not installed, skipping env validation"
  fi
fi

GitHub Actions

- name: Validate environment
  uses: zorl-engine/zorath-env/.github/actions/zenv-action@main
  with:
    schema: env.schema.json
    env-file: .env.example

Validation Failure Output

When validation fails, zenv provides clear error messages:

$ zenv check
zenv check failed:

- DATABASE_URL: expected url, got 'not-a-url'
- NODE_ENV: expected one of ["development", "staging", "production"], got 'dev'
- API_KEY: missing (required)
- UNKNOWN_VAR: not in schema (unknown key)

9. Secret Detection

Scan .env files for accidentally committed secrets with --detect-secrets flag.

Usage

zenv check --detect-secrets

Detected Patterns

zenv scans for the following secret patterns:

TypePatternDescription
AWS Access KeysAKIA...AWS access key IDs starting with AKIA
AWS Secret Keys40-char stringsAWS secret access keys
Stripe Keyssk_live_, sk_test_, pk_live_, pk_test_Stripe API keys
GitHub Tokensghp_, gho_, ghs_, ghr_GitHub personal access tokens
GitLab Tokensglpat-GitLab personal access tokens
Slack Tokensxoxb-, xoxp-, xoxa-Slack bot and user tokens
Google API KeysAIza...Google Cloud API keys
Heroku API KeysUUID formatHeroku platform API keys
SendGrid API KeysSG....SendGrid email API keys
Twilio CredentialsAC..., SK...Twilio account and API keys
Mailchimp API Keys...-us##Mailchimp marketing API keys
npm Tokensnpm_...npm registry access tokens
Private Keys-----BEGIN RSA PRIVATE KEY-----RSA, SSH, PGP private keys
JWT TokenseyJ...JSON Web Tokens
URL Passwords://user:pass@hostURLs with embedded credentials
High-Entropy Strings32+ chars, high entropyPossible API keys or secrets

Example Output

$ zenv check --detect-secrets

Warning: Potential secrets detected:

- AWS_SECRET_KEY (line 12): AWS Secret Access Key
- DATABASE_URL (line 15): URL contains embedded password
- API_TOKEN (line 22): High-entropy string (possible secret)

These values may be real secrets. Consider using placeholders in committed files.

Need Help?

Found a bug, have a feature request, or just want to discuss zorath-env?