Environments

Environment Configuration - C-Suite

Este documento descreve o sistema de gerenciamento de ambientes (dev, staging, production) para o ecossistema C-Suite.

Visão Geral

O módulo common/common_environments.py fornece gerenciamento centralizado de configurações por ambiente, garantindo que cada ambiente tenha configurações apropriadas.

Ambientes Suportados

Detecção Automática

O ambiente é detectado automaticamente da variável ENVIRONMENT ou ENV:

export ENVIRONMENT=production
# ou
export ENV=prod

Configurações por Ambiente

Development

Staging

Production

Test

Uso

Obter Ambiente Atual

from common.common_environments import get_current_environment, Environment

env = get_current_environment()
print(f"Current environment: {env.value}")

Obter Configuração

from common.common_environments import get_environment_config

config = get_environment_config()

print(f"Debug: {config.debug}")
print(f"Log level: {config.log_level}")
print(f"Cache TTL: {config.cache_ttl}")
print(f"Rate limit: {config.rate_limit_per_minute}")

Verificar Ambiente

from common.common_environments import is_production, is_development, is_staging, is_test

if is_production():
    # Código específico de produção
    pass

if is_development():
    # Código específico de desenvolvimento
    pass

Aplicar Configuração

from common.common_environments import EnvironmentManager, Environment

# Obter configuração de staging
config = EnvironmentManager.get_config(Environment.STAGING)

# Aplicar configuração
EnvironmentManager.apply_config(config)

Configuração Customizada

Criar Configuração Customizada

from common.common_environments import EnvironmentConfig, EnvironmentManager

# Criar configuração customizada
custom_config = EnvironmentConfig(
    name="custom",
    debug=False,
    log_level="INFO",
    cache_ttl=300,
    rate_limit_per_minute=100,
    enable_tracing=True,
    enable_metrics=True,
    enable_audit=True,
    secrets_backend="vault",
    ssl_required=True,
    cors_origins=["https://app.example.com"]
)

# Registrar configuração
EnvironmentManager._configs[Environment.STAGING] = custom_config

Integração com Outros Módulos

Com Logging

from common.common_environments import get_environment_config
from common.common_logging import setup_logging

config = get_environment_config()
setup_logging(level=config.log_level, json_format=not config.debug)

Com Cache

from common.common_environments import get_environment_config
from common.common_cache import Cache, CacheConfig

config = get_environment_config()
cache_config = CacheConfig(default_ttl=config.cache_ttl)
cache = Cache(cache_config)

Com Rate Limiting

from common.common_environments import get_environment_config
from common.common_rate_limit import create_rate_limit_middleware

config = get_environment_config()
app.middleware("http")(
    create_rate_limit_middleware(requests_per_minute=config.rate_limit_per_minute)
)

Com Tracing

from common.common_environments import get_environment_config
from common.common_tracing import setup_tracing

config = get_environment_config()
if config.enable_tracing:
    setup_tracing(service_name="my-service")

Variáveis de Ambiente

Configuração Base

# Ambiente
ENVIRONMENT=production
ENV=prod

# Debug
DEBUG=false

# Logging
LOG_LEVEL=WARNING

# Database
CSUITE_DB_NAME=csuite

# Cache
CACHE_TTL=600

# Rate Limiting
RATE_LIMIT_PER_MINUTE=60

# Tracing
TRACING_ENABLED=true

# Metrics
METRICS_ENABLED=true

# Audit
AUDIT_ENABLED=true

# Secrets
SECRETS_BACKEND=aws_secrets_manager

# SSL
SSL_REQUIRED=true

# CORS
CORS_ORIGINS=https://app.example.com,https://admin.example.com

Exemplo Completo

from fastapi import FastAPI
from common.common_environments import get_environment_config, is_production
from common.common_logging import setup_logging
from common.common_tracing import setup_tracing
from common.common_metrics import create_metrics_router
from common.common_health import create_health_router

app = FastAPI()

# Obter configuração do ambiente
config = get_environment_config()

# Setup logging
setup_logging(level=config.log_level, json_format=not config.debug)

# Setup tracing (se habilitado)
if config.enable_tracing:
    setup_tracing(service_name="csuite-api")

# Setup metrics (se habilitado)
if config.enable_metrics:
    metrics_router = create_metrics_router("csuite-api")
    app.include_router(metrics_router)

# Health checks
health_router = create_health_router()
app.include_router(health_router)

@app.get("/")
async def root():
    if is_production():
        return {"message": "Production API"}
    else:
        return {"message": "Development API", "debug": True}

Best Practices

  1. Nunca hardcode valores: Use configuração por ambiente
  2. Validação: Valide configurações na inicialização
  3. Secrets: Use secrets management apropriado por ambiente
  4. Logging: Configure níveis de log apropriados
  5. SSL: Sempre use SSL em staging/production
  6. CORS: Configure CORS apropriadamente por ambiente

Troubleshooting

Ambiente não detectado

Verifique variável ENVIRONMENT ou ENV:

echo $ENVIRONMENT

Configuração incorreta

Verifique logs na inicialização para ver qual configuração está sendo aplicada.

Secrets não funcionam

Verifique SECRETS_BACKEND e se o backend está configurado corretamente.

Referências

🔊 Text-to-Speech

1.0x
1.0
Pronto para reproduzir