Files
unitforge/docs/ENVIRONMENT.md
William Valentin 6841bce2e7 docs: add comprehensive environment variable documentation
- Document all 70+ configuration options with descriptions and defaults
- Provide examples for development, production, Docker, and Kubernetes
- Include best practices for security, deployment, and troubleshooting
- Add migration guide for existing deployments
- Document validation system and debugging techniques
- Cover template integration and Python code usage patterns
2025-09-14 15:58:07 -07:00

482 lines
14 KiB
Markdown

# Environment Variable Configuration
This document describes how to configure UnitForge using environment variables.
## Overview
UnitForge supports configuration through environment variables, allowing you to customize the application's behavior without modifying the source code. This is particularly useful for different deployment environments (development, staging, production) and for containerized deployments.
## Configuration Files
### .env File
The recommended way to configure UnitForge is by using a `.env` file in the project root. This file contains key-value pairs that define your environment variables.
1. Copy the example file:
```bash
cp .env.example .env
```
2. Edit the `.env` file with your preferred settings:
```bash
nano .env
```
### Docker Compose
When using Docker Compose, the `.env` file is automatically loaded. You can also override specific variables in the `docker-compose.yml` file or use separate environment files for different profiles.
## Available Environment Variables
### Application Information
| Variable | Default | Description |
|----------|---------|-------------|
| `APP_NAME` | `UnitForge` | Application name displayed in the UI and CLI |
| `APP_VERSION` | `1.0.0` | Application version number |
| `APP_DESCRIPTION` | `Create, validate, and manage systemd unit files` | Application description |
### External Links
| Variable | Default | Description |
|----------|---------|-------------|
| `GITHUB_URL` | `https://github.com/will666/unitforge` | GitHub repository URL |
| `DOCUMENTATION_URL` | `https://unitforge.readthedocs.io/` | Documentation website URL |
| `BUG_REPORTS_URL` | `https://github.com/will666/unitforge/issues` | Bug reports URL |
### Contact Information
| Variable | Default | Description |
|----------|---------|-------------|
| `CONTACT_EMAIL` | `contact@unitforge.dev` | Contact email address |
### Application Settings
| Variable | Default | Description |
|----------|---------|-------------|
| `DEBUG` | `false` | Enable debug mode (true/false) |
| `ENVIRONMENT` | `production` | Environment (development/staging/production) |
| `LOG_LEVEL` | `info` | Logging level (debug/info/warning/error) |
### Server Configuration
| Variable | Default | Description |
|----------|---------|-------------|
| `HOST` | `0.0.0.0` | Host address to bind the server |
| `PORT` | `8000` | Port number for the web server |
| `RELOAD` | `false` | Enable auto-reload on code changes |
| `WORKERS` | `4` | Number of worker processes |
### API Configuration
| Variable | Default | Description |
|----------|---------|-------------|
| `API_TITLE` | `${APP_NAME}` | API title in documentation |
| `API_VERSION` | `${APP_VERSION}` | API version |
| `API_DESCRIPTION` | `${APP_DESCRIPTION}` | API description |
| `DOCS_URL` | `/api/docs` | Swagger UI endpoint |
| `REDOC_URL` | `/api/redoc` | ReDoc endpoint |
### Security Settings
| Variable | Default | Description |
|----------|---------|-------------|
| `SECRET_KEY` | None | Secret key for cryptographic operations |
| `ALLOWED_HOSTS` | `["*"]` | Allowed host headers (JSON array) |
| `SECURITY_HEADERS` | `true` | Enable security headers |
| `HSTS_MAX_AGE` | `31536000` | HSTS max age in seconds |
| `CSP_ENABLED` | `true` | Enable Content Security Policy |
### CORS Configuration
| Variable | Default | Description |
|----------|---------|-------------|
| `CORS_ORIGINS` | `*` | Allowed CORS origins (comma-separated, JSON array, or `*`) |
### File Upload Settings
| Variable | Default | Description |
|----------|---------|-------------|
| `MAX_UPLOAD_SIZE` | `1048576` | Maximum file upload size in bytes (1MB) |
| `ALLOWED_EXTENSIONS` | `[".service", ".timer", ...]` | Allowed file extensions (JSON array) |
### Template Settings
| Variable | Default | Description |
|----------|---------|-------------|
| `TEMPLATE_CACHE_TTL` | `300` | Template cache time-to-live in seconds |
| `VALIDATION_CACHE_TTL` | `60` | Validation cache time-to-live in seconds |
### Paths
| Variable | Default | Description |
|----------|---------|-------------|
| `FRONTEND_DIR` | `frontend` | Frontend directory path |
| `BACKEND_DIR` | `backend` | Backend directory path |
| `STATIC_DIR` | `frontend/static` | Static files directory |
| `TEMPLATES_DIR` | `frontend/templates` | Templates directory |
### Feature Flags
| Variable | Default | Description |
|----------|---------|-------------|
| `ENABLE_API_METRICS` | `false` | Enable API metrics collection |
| `ENABLE_REQUEST_LOGGING` | `true` | Enable request logging |
| `ENABLE_TEMPLATE_CACHING` | `true` | Enable template caching |
| `ENABLE_VALIDATION_CACHING` | `true` | Enable validation result caching |
### Performance Settings
| Variable | Default | Description |
|----------|---------|-------------|
| `REQUEST_TIMEOUT` | `30` | Request timeout in seconds |
| `KEEPALIVE_TIMEOUT` | `5` | Keep-alive timeout in seconds |
| `MAX_CONNECTIONS` | `100` | Maximum concurrent connections |
### Logging Configuration
| Variable | Default | Description |
|----------|---------|-------------|
| `LOG_FORMAT` | `%(asctime)s - %(name)s - %(levelname)s - %(message)s` | Log message format |
| `LOG_DATE_FORMAT` | `%Y-%m-%d %H:%M:%S` | Log date format |
| `ACCESS_LOG` | `true` | Enable access logging |
### CLI Configuration
| Variable | Default | Description |
|----------|---------|-------------|
| `CLI_VERBOSE` | `false` | Enable verbose CLI output |
| `CLI_COLOR` | `true` | Enable colored CLI output |
| `CLI_PROGRESS` | `true` | Show progress indicators |
### Validation Settings
| Variable | Default | Description |
|----------|---------|-------------|
| `STRICT_VALIDATION` | `false` | Enable strict validation mode |
| `SHOW_WARNINGS` | `true` | Show validation warnings |
| `MAX_VALIDATION_ERRORS` | `50` | Maximum validation errors to report |
### Template Generation Defaults
| Variable | Default | Description |
|----------|---------|-------------|
| `DEFAULT_USER` | `www-data` | Default service user |
| `DEFAULT_GROUP` | `www-data` | Default service group |
| `DEFAULT_RESTART_POLICY` | `on-failure` | Default restart policy |
| `DEFAULT_WANTED_BY` | `multi-user.target` | Default WantedBy target |
### Monitoring
| Variable | Default | Description |
|----------|---------|-------------|
| `HEALTH_CHECK_ENABLED` | `true` | Enable health check endpoint |
| `METRICS_ENABLED` | `false` | Enable metrics collection |
| `TRACING_ENABLED` | `false` | Enable request tracing |
### Asset Optimization
| Variable | Default | Description |
|----------|---------|-------------|
| `HOT_RELOAD` | `false` | Enable hot reload for assets |
| `SOURCE_MAPS` | `false` | Generate source maps |
| `MINIFY_ASSETS` | `true` | Minify CSS/JS assets |
| `COMPRESS_RESPONSES` | `true` | Enable response compression |
### Documentation
| Variable | Default | Description |
|----------|---------|-------------|
| `DOCS_AUTO_RELOAD` | `false` | Auto-reload documentation |
| `API_DOCS_ENABLED` | `true` | Enable API documentation |
| `SWAGGER_UI_ENABLED` | `true` | Enable Swagger UI |
| `REDOC_ENABLED` | `true` | Enable ReDoc interface |
## Examples
### Development Environment
```bash
# .env for development
APP_NAME=UnitForge Dev
DEBUG=true
ENVIRONMENT=development
LOG_LEVEL=debug
HOST=127.0.0.1
RELOAD=true
WORKERS=1
API_TITLE="${APP_NAME} Development"
API_VERSION="${APP_VERSION}-dev"
CORS_ORIGINS=["http://localhost:3000", "http://localhost:8000"]
ENABLE_API_METRICS=true
HOT_RELOAD=true
SOURCE_MAPS=true
MINIFY_ASSETS=false
SECURITY_HEADERS=false
DOCS_AUTO_RELOAD=true
GITHUB_URL=https://github.com/myorg/unitforge
```
### Production Environment
```bash
# .env for production
APP_NAME=UnitForge
DEBUG=false
ENVIRONMENT=production
LOG_LEVEL=info
HOST=0.0.0.0
PORT=80
WORKERS=4
CORS_ORIGINS=["https://unitforge.example.com"]
SECRET_KEY=your-secure-secret-key-here
SECURITY_HEADERS=true
HSTS_MAX_AGE=31536000
CSP_ENABLED=true
MINIFY_ASSETS=true
COMPRESS_RESPONSES=true
METRICS_ENABLED=true
GITHUB_URL=https://github.com/mycompany/unitforge
DOCUMENTATION_URL=https://docs.example.com/unitforge
```
### Docker Environment
```bash
# .env for Docker deployment
APP_NAME=UnitForge Container
DEBUG=false
ENVIRONMENT=production
HOST=0.0.0.0
PORT=8000
CORS_ORIGINS=*
ENABLE_TEMPLATE_CACHING=true
ENABLE_VALIDATION_CACHING=true
HEALTH_CHECK_ENABLED=true
```
### Kubernetes Environment
```bash
# .env for Kubernetes deployment
APP_NAME=UnitForge K8s
ENVIRONMENT=production
HOST=0.0.0.0
PORT=8000
WORKERS=8
MAX_CONNECTIONS=500
REQUEST_TIMEOUT=30
ENABLE_API_METRICS=true
METRICS_ENABLED=true
TRACING_ENABLED=true
COMPRESS_RESPONSES=true
```
## Usage in Different Components
### Web Templates
Environment variables are automatically injected into HTML templates. You can use them like this:
```html
<title>{{ app_name }} - Page Title</title>
<a href="{{ github_url }}">GitHub</a>
<p>{{ app_description }}</p>
```
### Python Code
Import and use the settings object:
```python
from app.core.config import settings
print(f"Running {settings.app_name} v{settings.app_version}")
print(f"GitHub: {settings.github_url}")
```
### CLI
The CLI automatically uses the configured app name and version:
```bash
./unitforge-cli --version
# Output: UnitForge, version 1.0.0
```
## Docker Compose Integration
The `docker-compose.yml` file is configured to automatically load the `.env` file:
```yaml
services:
unitforge-dev:
env_file:
- .env
environment:
- DEBUG=true # Override specific variables
```
## Best Practices
### Security
1. **Never commit `.env` files**: The `.env` file may contain sensitive information. Always add it to `.gitignore`.
2. **Use strong secret keys**: Generate cryptographically secure secret keys for production:
```bash
python -c "import secrets; print(secrets.token_urlsafe(32))"
```
3. **Separate environments**: Use different `.env` files for different environments:
- `.env.development`
- `.env.staging`
- `.env.production`
4. **Configure security headers**: Enable security headers in production:
```bash
SECURITY_HEADERS=true
HSTS_MAX_AGE=31536000
CSP_ENABLED=true
```
5. **Validate file uploads**: Configure upload restrictions:
```bash
MAX_UPLOAD_SIZE=1048576 # 1MB
ALLOWED_EXTENSIONS=[".service", ".timer", ".socket"]
```
### Development
1. **Copy from example**: Always start with `.env.example` to ensure you have all required variables.
2. **Document changes**: When adding new environment variables, update both `.env.example` and this documentation.
3. **Validate configuration**: Test your configuration changes in both development and production-like environments.
4. **Use development overrides**: Enable development-specific features:
```bash
DEBUG=true
HOT_RELOAD=true
DOCS_AUTO_RELOAD=true
ENABLE_API_METRICS=true
```
5. **Performance testing**: Use performance settings for load testing:
```bash
WORKERS=8
MAX_CONNECTIONS=1000
REQUEST_TIMEOUT=60
```
### Deployment
1. **Use container secrets**: For container deployments, prefer Docker secrets or Kubernetes secrets over environment variables for sensitive data.
2. **Environment-specific overrides**: Use your deployment platform's environment variable features to override settings per environment.
3. **Health checks**: Ensure your configuration doesn't break health check endpoints:
```bash
HEALTH_CHECK_ENABLED=true
```
4. **Production optimization**: Configure for production workloads:
```bash
WORKERS=4 # or number of CPU cores
COMPRESS_RESPONSES=true
MINIFY_ASSETS=true
ENABLE_TEMPLATE_CACHING=true
```
5. **Monitoring setup**: Enable monitoring features:
```bash
METRICS_ENABLED=true
ENABLE_REQUEST_LOGGING=true
LOG_LEVEL=info
```
## Troubleshooting
### Common Issues
1. **Variables not loading**: Ensure the `.env` file is in the project root and has the correct syntax (no spaces around `=`).
2. **CORS errors**: Check your `CORS_ORIGINS` setting matches your frontend URL exactly. Use JSON array format for multiple origins:
```bash
CORS_ORIGINS=["http://localhost:3000", "https://app.example.com"]
```
3. **Port conflicts**: Ensure the `PORT` setting doesn't conflict with other services.
4. **File upload errors**: Check upload size and extension settings:
```bash
MAX_UPLOAD_SIZE=5242880 # 5MB
ALLOWED_EXTENSIONS=[".service", ".timer", ".socket", ".mount", ".target", ".path"]
```
5. **Performance issues**: Adjust worker and connection settings:
```bash
WORKERS=4
MAX_CONNECTIONS=200
REQUEST_TIMEOUT=30
```
6. **Documentation not loading**: Ensure docs are enabled:
```bash
API_DOCS_ENABLED=true
SWAGGER_UI_ENABLED=true
```
### Debugging
Enable debug mode to see configuration loading:
```bash
DEBUG=true python -c "from app.core.config import settings; print(vars(settings))"
```
Check if environment variables are loaded:
```bash
python -c "import os; print('APP_NAME:', os.getenv('APP_NAME', 'Not set'))"
```
Test specific configuration sections:
```bash
# Test API settings
python -c "from app.core.config import settings; print(f'API: {settings.api_title} v{settings.api_version}')"
# Test feature flags
python -c "from app.core.config import settings; print(f'Metrics: {settings.enable_api_metrics}, Caching: {settings.enable_template_caching}')"
# Test paths
python -c "from app.core.config import settings; print(f'Templates: {settings.templates_dir}, Static: {settings.static_dir}')"
```
Validate JSON array configurations:
```bash
python -c "
from app.core.config import settings
print('CORS Origins:', settings.cors_origins)
print('Allowed Extensions:', settings.allowed_extensions)
print('Allowed Hosts:', settings.allowed_hosts)
"
```
## Migration Guide
If you're upgrading from a version without environment variable support:
1. Create a `.env` file from the example
2. Set your custom values (GitHub URL, app name, etc.)
3. Remove any hardcoded values from your deployment scripts
4. Test the configuration in a development environment
5. Deploy with the new environment-based configuration
## See Also
- [Development Setup](../README.md#development-setup)
- [Docker Deployment](../docker-compose.yml)
- [Configuration Module](../backend/app/core/config.py)