Konfigurationsreferenz¶
Audience: Dev, Ops
You will learn:
- Alle Konfigurationsoptionen und Environment-Variablen
- Standardwerte und Gültigkeitsbereiche
- Konfigurationshierarchie und Precedence
- Best Practices für verschiedene Umgebungen
Pre-requisites: - Entwicklungsumgebung eingerichtet - Grundverständnis von Environment-Variablen - System-Administration Kenntnisse
Konfigurationsübersicht¶
Konfigurationsquellen (Precedence)¶
- Environment-Variablen (höchste Priorität)
- Command-Line-Parameter
- Konfigurationsdateien
- Standardwerte (niedrigste Priorität)
# Beispiel-Hierarchy
config_value = (
os.environ.get('CONFIG_KEY') or # Environment Variable
args.config_key or # Command Line Argument
config_file.get('config_key') or # Config File
DEFAULT_VALUE # Default Value
)
Evidenz: Configuration patterns from development workflow
Environment-Variablen¶
Flask-Application¶
Variable | Standard | Beschreibung | Beispiele |
---|---|---|---|
FLASK_ENV |
production |
Flask-Umgebung | development , production |
FLASK_DEBUG |
false |
Debug-Modus aktivieren | true , false |
SECRET_KEY |
None |
Flask Secret Key für Sessions | your-secret-key-here |
HOST |
0.0.0.0 |
Server-Bind-Address | 127.0.0.1 , 0.0.0.0 |
PORT |
5000 |
Server-Port | 5000 , 8080 |
# Development Environment
export FLASK_ENV=development
export FLASK_DEBUG=true
export SECRET_KEY=dev-secret-not-for-production
# Production Environment
export FLASK_ENV=production
export FLASK_DEBUG=false
export SECRET_KEY=$(openssl rand -hex 32)
Evidenz: app.py:66-67 Flask configuration
Icon-Management¶
Variable | Standard | Beschreibung | Gültige Werte |
---|---|---|---|
ICONS_DIR |
static/icons |
Verzeichnis für SVG-Dateien | Absoluter/relativer Pfad |
METADATA_FILE |
icons.json |
Metadaten-Datei | Dateipfad |
MAX_ICONS |
1000 |
Maximale Icon-Anzahl | Positive Ganzzahl |
MAX_CATEGORIES |
50 |
Maximale Kategorie-Anzahl | Positive Ganzzahl |
EXTRACT_ON_STARTUP |
false |
Icons bei Start extrahieren | true , false |
# Custom Icon Configuration
export ICONS_DIR="/mnt/storage/icons"
export METADATA_FILE="/etc/icon-tool/categories.json"
export MAX_ICONS=500
export MAX_CATEGORIES=25
Performance & Caching¶
Variable | Standard | Beschreibung | Einheit |
---|---|---|---|
ENABLE_CACHING |
true |
Application-Level-Caching | Boolean |
CACHE_TIMEOUT |
300 |
Cache-Gültigkeit | Sekunden |
API_CACHE_TIMEOUT |
60 |
API-Response-Cache | Sekunden |
MAX_MEMORY_MB |
100 |
Memory-Limit | Megabytes |
REQUEST_TIMEOUT |
30 |
Request-Timeout | Sekunden |
# Performance Tuning
export ENABLE_CACHING=true
export CACHE_TIMEOUT=600 # 10 Minuten
export MAX_MEMORY_MB=200
Logging & Monitoring¶
Variable | Standard | Beschreibung | Optionen |
---|---|---|---|
LOG_LEVEL |
INFO |
Logging-Level | DEBUG , INFO , WARNING , ERROR |
LOG_FILE |
logs/icon-tool.log |
Log-Datei-Pfad | Dateipfad |
LOG_ROTATION |
true |
Log-Rotation aktivieren | true , false |
LOG_MAX_SIZE |
10MB |
Maximale Log-Größe | Size-String |
MONITORING_ENABLED |
false |
Monitoring aktivieren | true , false |
# Logging Configuration
export LOG_LEVEL=DEBUG
export LOG_FILE="/var/log/icon-tool.log"
export LOG_ROTATION=true
export LOG_MAX_SIZE=50MB
Security¶
Variable | Standard | Beschreibung | Sicherheitslevel |
---|---|---|---|
ADMIN_ENABLED |
false |
Admin-Interface aktivieren | true , false |
ADMIN_PASSWORD |
None |
Admin-Passwort | Sicheres Passwort |
RATE_LIMIT_ENABLED |
false |
Rate-Limiting aktivieren | true , false |
RATE_LIMIT_REQUESTS |
1000 |
Requests pro Minute | Positive Ganzzahl |
ALLOWED_ORIGINS |
* |
CORS-Origins | Domain-Liste |
# Security Configuration
export ADMIN_ENABLED=true
export ADMIN_PASSWORD=$(openssl rand -base64 32)
export RATE_LIMIT_ENABLED=true
export RATE_LIMIT_REQUESTS=500
export ALLOWED_ORIGINS="https://ak-systems.com,https://icons.ak-systems.com"
Evidenz: Security requirements, admin interface planning
Konfigurationsdateien¶
1. Application Config (.env)¶
# .env (Development)
FLASK_ENV=development
FLASK_DEBUG=true
SECRET_KEY=dev-secret
# Icon Configuration
ICONS_DIR=static/icons
METADATA_FILE=icons.json
MAX_ICONS=500
# Performance
ENABLE_CACHING=true
CACHE_TIMEOUT=60
# Logging
LOG_LEVEL=DEBUG
LOG_FILE=logs/icon-tool.log
# .env.production
FLASK_ENV=production
FLASK_DEBUG=false
SECRET_KEY=${SECRET_KEY} # From environment
# Icon Configuration
ICONS_DIR=/opt/icon-tool/static/icons
METADATA_FILE=/opt/icon-tool/icons.json
MAX_ICONS=1000
# Performance
ENABLE_CACHING=true
CACHE_TIMEOUT=300
# Logging
LOG_LEVEL=INFO
LOG_FILE=/var/log/icon-tool.log
# Security
ADMIN_ENABLED=true
RATE_LIMIT_ENABLED=true
2. Python Configuration¶
# config.py
import os
from pathlib import Path
class Config:
"""Base configuration"""
# Flask Settings
SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-secret-key'
DEBUG = False
TESTING = False
# Icon Management
ICONS_DIR = Path(os.environ.get('ICONS_DIR', 'static/icons'))
METADATA_FILE = Path(os.environ.get('METADATA_FILE', 'icons.json'))
MAX_ICONS = int(os.environ.get('MAX_ICONS', '1000'))
MAX_CATEGORIES = int(os.environ.get('MAX_CATEGORIES', '50'))
# Performance
ENABLE_CACHING = os.environ.get('ENABLE_CACHING', 'true').lower() == 'true'
CACHE_TIMEOUT = int(os.environ.get('CACHE_TIMEOUT', '300'))
# Logging
LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO')
LOG_FILE = os.environ.get('LOG_FILE', 'logs/icon-tool.log')
class DevelopmentConfig(Config):
"""Development configuration"""
DEBUG = True
LOG_LEVEL = 'DEBUG'
CACHE_TIMEOUT = 60
class ProductionConfig(Config):
"""Production configuration"""
DEBUG = False
LOG_LEVEL = 'INFO'
CACHE_TIMEOUT = 300
class TestingConfig(Config):
"""Testing configuration"""
TESTING = True
ICONS_DIR = Path('tests/fixtures/icons')
METADATA_FILE = Path('tests/fixtures/icons.json')
# Configuration Selection
config = {
'development': DevelopmentConfig,
'production': ProductionConfig,
'testing': TestingConfig,
'default': DevelopmentConfig
}
3. systemd Service Configuration¶
# /etc/systemd/system/icon-tool.service
[Unit]
Description=ak Systems Icon Management Tool
After=network.target
[Service]
Type=simple
User=iconuser
Group=icongroup
WorkingDirectory=/opt/icon-tool
# Environment Configuration
Environment=FLASK_ENV=production
Environment=FLASK_DEBUG=false
Environment=LOG_LEVEL=INFO
Environment=ENABLE_CACHING=true
Environment=CACHE_TIMEOUT=300
Environment=MAX_ICONS=1000
# Resource Limits
MemoryLimit=100M
TimeoutStopSec=10
# Security
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=/opt/icon-tool/logs
NoNewPrivileges=true
# Execution
ExecStart=/opt/icon-tool/venv/bin/python app.py
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
4. Docker Configuration¶
# Dockerfile - Environment Configuration
FROM python:3.11-slim
# Default Environment Variables
ENV FLASK_ENV=production
ENV FLASK_DEBUG=false
ENV HOST=0.0.0.0
ENV PORT=5000
ENV ICONS_DIR=/app/static/icons
ENV LOG_LEVEL=INFO
ENV ENABLE_CACHING=true
# Runtime Configuration
WORKDIR /app
EXPOSE 5000
# Override via docker run
CMD ["python", "app.py"]
# docker-compose.yml
version: '3.8'
services:
icon-tool:
build: .
ports:
- "5000:5000"
environment:
FLASK_ENV: production
LOG_LEVEL: INFO
ENABLE_CACHING: "true"
CACHE_TIMEOUT: "300"
MAX_ICONS: "1000"
volumes:
- ./data/icons:/app/static/icons
- ./data/logs:/app/logs
restart: unless-stopped
Validation & Defaults¶
Configuration-Validation¶
# config_validator.py
import os
from pathlib import Path
class ConfigValidator:
"""Validate configuration values"""
@staticmethod
def validate_config():
"""Validate all configuration settings"""
errors = []
# Check required directories
icons_dir = Path(os.environ.get('ICONS_DIR', 'static/icons'))
if not icons_dir.exists():
errors.append(f"Icons directory does not exist: {icons_dir}")
# Check file permissions
if icons_dir.exists() and not os.access(icons_dir, os.R_OK):
errors.append(f"Icons directory not readable: {icons_dir}")
# Validate numeric values
try:
max_icons = int(os.environ.get('MAX_ICONS', '1000'))
if max_icons <= 0:
errors.append("MAX_ICONS must be positive")
except ValueError:
errors.append("MAX_ICONS must be a valid integer")
# Check log file directory
log_file = Path(os.environ.get('LOG_FILE', 'logs/icon-tool.log'))
log_dir = log_file.parent
if not log_dir.exists():
try:
log_dir.mkdir(parents=True, exist_ok=True)
except PermissionError:
errors.append(f"Cannot create log directory: {log_dir}")
return errors
# Usage
if __name__ == '__main__':
errors = ConfigValidator.validate_config()
if errors:
print("Configuration errors:")
for error in errors:
print(f" - {error}")
exit(1)
else:
print("✅ Configuration is valid")
Default-Werte-Übersicht¶
# defaults.py
DEFAULTS = {
# Flask Application
'FLASK_ENV': 'production',
'FLASK_DEBUG': 'false',
'HOST': '0.0.0.0',
'PORT': '5000',
# Icon Management
'ICONS_DIR': 'static/icons',
'METADATA_FILE': 'icons.json',
'MAX_ICONS': '1000',
'MAX_CATEGORIES': '50',
'EXTRACT_ON_STARTUP': 'false',
# Performance
'ENABLE_CACHING': 'true',
'CACHE_TIMEOUT': '300',
'API_CACHE_TIMEOUT': '60',
'MAX_MEMORY_MB': '100',
'REQUEST_TIMEOUT': '30',
# Logging
'LOG_LEVEL': 'INFO',
'LOG_FILE': 'logs/icon-tool.log',
'LOG_ROTATION': 'true',
'LOG_MAX_SIZE': '10MB',
# Security
'ADMIN_ENABLED': 'false',
'RATE_LIMIT_ENABLED': 'false',
'RATE_LIMIT_REQUESTS': '1000',
'ALLOWED_ORIGINS': '*'
}
def get_config_value(key, default=None):
"""Get configuration value with fallback to defaults"""
return os.environ.get(key, DEFAULTS.get(key, default))
Umgebungsprofile¶
Development Profile¶
# scripts/dev-config.sh
#!/bin/bash
echo "Setting up development environment..."
export FLASK_ENV=development
export FLASK_DEBUG=true
export LOG_LEVEL=DEBUG
export CACHE_TIMEOUT=60
export SECRET_KEY=dev-secret-key
# Icon settings for faster testing
export MAX_ICONS=50
export EXTRACT_ON_STARTUP=true
echo "✅ Development environment configured"
Staging Profile¶
# scripts/staging-config.sh
#!/bin/bash
echo "Setting up staging environment..."
export FLASK_ENV=production
export FLASK_DEBUG=false
export LOG_LEVEL=INFO
export CACHE_TIMEOUT=180
# Production-like but with more debugging
export MONITORING_ENABLED=true
export ADMIN_ENABLED=true
echo "✅ Staging environment configured"
Production Profile¶
# scripts/production-config.sh
#!/bin/bash
echo "Setting up production environment..."
export FLASK_ENV=production
export FLASK_DEBUG=false
export LOG_LEVEL=WARNING
export CACHE_TIMEOUT=300
# Security settings
export ADMIN_ENABLED=true
export RATE_LIMIT_ENABLED=true
export RATE_LIMIT_REQUESTS=500
# Performance optimization
export ENABLE_CACHING=true
export MAX_MEMORY_MB=200
# Ensure SECRET_KEY is set
if [ -z "$SECRET_KEY" ]; then
echo "❌ SECRET_KEY not set in production"
exit 1
fi
echo "✅ Production environment configured"
Configuration Management¶
1. Secrets Management¶
# secrets.env (nicht in Git)
SECRET_KEY=actual-secret-key-here
ADMIN_PASSWORD=secure-admin-password
DATABASE_URL=postgresql://user:pass@localhost/db
# Load in application
python -c "
from dotenv import load_dotenv
load_dotenv('secrets.env')
print('Secrets loaded')
"
2. Config Rotation¶
#!/bin/bash
# scripts/rotate-secrets.sh
echo "Rotating application secrets..."
# Generate new secret key
NEW_SECRET=$(openssl rand -hex 32)
OLD_SECRET=$SECRET_KEY
# Update environment
export SECRET_KEY=$NEW_SECRET
# Restart application with new secret
systemctl restart icon-tool
# Validate new secret works
if curl -f http://localhost:5000/health; then
echo "✅ Secret rotation successful"
echo "Old secret: ${OLD_SECRET:0:8}..."
echo "New secret: ${NEW_SECRET:0:8}..."
else
echo "❌ Secret rotation failed, rolling back"
export SECRET_KEY=$OLD_SECRET
systemctl restart icon-tool
fi
3. Configuration Backup¶
#!/bin/bash
# scripts/backup-config.sh
BACKUP_DIR="/backup/config"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p "$BACKUP_DIR"
# Backup environment files
cp .env* "$BACKUP_DIR/env-$DATE"
# Backup systemd service
cp /etc/systemd/system/icon-tool.service "$BACKUP_DIR/service-$DATE"
# Export current environment (ohne Secrets)
env | grep -E '^(FLASK|ICON|LOG|CACHE|MAX)_' > "$BACKUP_DIR/env-vars-$DATE.txt"
echo "✅ Configuration backed up to $BACKUP_DIR"
Troubleshooting Configuration¶
Common Configuration Issues¶
Problem: Environment Variables werden nicht geladen¶
# Diagnose
echo "Current FLASK_ENV: $FLASK_ENV"
python -c "import os; print('FLASK_ENV:', os.environ.get('FLASK_ENV', 'NOT SET'))"
# Solution: Load Environment file
source .env
# oder: export $(cat .env | xargs)
Problem: Falsche Konfigurationswerte¶
# Debug Configuration Loading
python -c "
import os
from config import Config
config = Config()
print('Icons Dir:', config.ICONS_DIR)
print('Debug Mode:', config.DEBUG)
print('Cache Timeout:', config.CACHE_TIMEOUT)
"
Problem: Permission-Denied bei Dateipfaden¶
# Check Permissions
ls -la $(echo $ICONS_DIR)
ls -la $(dirname "$LOG_FILE")
# Fix Permissions
sudo chown -R iconuser:icongroup "$ICONS_DIR"
sudo chmod 755 "$ICONS_DIR"
Configuration Verification¶
#!/bin/bash
# scripts/verify-config.sh
echo "=== Configuration Verification ==="
# Environment Variables
echo "Environment Variables:"
env | grep -E '^(FLASK|ICON|LOG|CACHE)_' | sort
# File Permissions
echo -e "\nFile Permissions:"
echo "Icons Dir: $(ls -ld "$ICONS_DIR" 2>/dev/null || echo "NOT FOUND")"
echo "Metadata File: $(ls -l "$METADATA_FILE" 2>/dev/null || echo "NOT FOUND")"
echo "Log Dir: $(ls -ld "$(dirname "$LOG_FILE")" 2>/dev/null || echo "NOT FOUND")"
# Application Test
echo -e "\nApplication Test:"
python -c "
try:
from app import app
with app.test_client() as client:
response = client.get('/health')
print(f'Health Check: {response.status_code}')
except Exception as e:
print(f'Application Error: {e}')
"
echo -e "\n✅ Configuration verification complete"
Evidenz: Configuration management patterns, environment best practices
Konfiguration-Checkliste: - [ ] Environment-Variablen für Umgebung definiert - [ ] Konfigurationsdateien erstellt und validiert - [ ] Secrets sicher verwaltet (nicht in Git) - [ ] Datei-Permissions korrekt gesetzt - [ ] Configuration-Validation implementiert - [ ] Backup-Strategie für Konfiguration vorhanden